0

I'm trying to fetch a data from my hosted database. The database itself are working (I have checked it from the swagger app) but no data is shown when it is called from API form.

import React from 'react';

export const getStaticPaths = async () => {
    const res = await fetch('https://[server]/course');
    const data = await res.json();

    const paths = data.result.map(course => {
        return {
            params: { id: course._id.toString() }
        }
    })

    return {
        paths,
        fallback: false
    }
}

export const getStaticProps = async (context) => {
    const id = context.params.id;
    const res = await fetch('https://[server]/course/' + id);
    const data = await res.json();

    return {
        props: { course: data }
    }
}

const Details = ({ course }) => {
    return (
        <div>
            <h1> { course.course_name } </h1>
            <h1>a</h1>

        </div>
    );
}
 
export default Details;

The code is in the pages folder. I followed a tutorial on youtube from "netninja" and when I tried it on his code it works. I read somewhere that it won't work on components but I already put it on the pages but it still does not return anything.

Is there anything I can do ?

Friel
  • 51
  • 4
  • 1
    Is the `fetch` inside `getStaticProps` returning the expected response/data? – juliomalves Aug 15 '21 at 17:42
  • It should be. I cannot check whether it does or not because I cannot call the data. But it is an API link and when the API link is run, it does return a specific data – Friel Aug 15 '21 at 17:44
  • 1
    You can verify what's being retuned in the response if you log `data` to the console and check the output in the terminal where you started the dev server. You might want to do the same with the request inside `getStaticPaths` too. – juliomalves Aug 15 '21 at 17:48
  • Hello, I have tested it, and for some reason it does not recognise the array as a database (if that makes any sense). So my best explaination is that I tried console log on another page where the API actually works and the data that came out had color on it indicating the data type but on the current page it is only black and white (which i assume means that the code does not recognize it as a database). Is there anything I can do? – Friel Aug 15 '21 at 18:11
  • 1
    Hello I just figured out the problem. The data is on "course.result.course_name" after I checked it on the console log. Thank you very much for your help and I'll be sure to use console.log more from now on. THANKS AGAIN!!! – Friel Aug 15 '21 at 18:25

1 Answers1

0

I got the answer. After checking console.log on the data. Looks like the data is on another array which is called result. so i needed to call the data from course.result.course_name. So the Answer is just to check console.log every once in a while. Shout out to juliomalves for pointing that out

Friel
  • 51
  • 4