skip to Main Content

I am trying to fetch data from a db.json local server on port 4000.
I’m using ReactJs, TypeScript and Axios.
My database is structured as followed :

{
  "quotes": [
    {
      "quote": "In the end, we will remember not the words of our enemies, but the silence of our friends.",
      "author": "Martin Luther King Jr."
    },
    {
      "quote": "We are all in the gutter, but some of us are looking at the stars.",
      "author": "Oscar Wilde"
    }
  ]
}

I implemented interfaces :

 interface Quote {
    quote: string;
    author: string;
 }
  
 interface ResponseData {
    quotes: Quote[];
 }

Here is my code to fetch data :

useEffect(() => {
    const fetchData = async() => {
      try{
        const response = await axios.get<ResponseData>('http://localhost:4000/quotes');
        console.log("response: " + response)
        console.log("response.data: " + response.data)
        console.log("response.data.quotes: " + response.data.quotes)
        const fetchedQuotes = response.data;

        if (fetchedQuotes) {

          const {quote, author} = fetchedQuotes.quotes[0];
        
        setQuoteList(fetchedQuotes.quotes);
        setAuthor(author);
        }
      } catch (error) { console.error("Error fetching data :", error); }  

    ;
  }

  fetchData();
  }, []);

My problem is that Response.data is working fine, returning an array of objects containing the quote and the author, but as soon as I try to access response.data.quotes, the console returns an undefined type error. If someone can help me, that would be really nice.

Thanks a lot to y’all

I tried to change the interfaces, to console log the objects, to understand better the data structure and what is returned by the axios API, but I’m new to this business so it was difficult for me to have clear ideas of what was happening.

2

Answers


  1. Try this:

    In db.json

    [
        {
          "quote": "In the end, we will remember not the words of our enemies, but the silence of our friends.",
          "author": "Martin Luther King Jr."
        },
        {
          "quote": "We are all in the gutter, but some of us are looking at the stars.",
          "author": "Oscar Wilde"
        }, etc...
    ]
    

    Now you have to change in your react component

    type Quotes ={
    quote: string;
    author: string;
    }[];
    
    [quoteList, setQuoteList]= useState<Quotes>([]);
    useEffect(() => {
        const fetchData = async() => {
          try{
            const response = await axios.get('http://localhost:4000/quotes');
            const fetchedQuotes = response.data;
            setQuoteList(fetchedQuotes);
            }
          } catch (error) { console.error("Error fetching data :", error); }  
    
      }
    
      fetchData();
      }, []);
    

    The return statement should be:

    export default function functionName(){
    {
    quoteList.map((qoutes, index)=>(
    <quote>{qoutes.quote}</quote>
    <span>{qoutes.quote}</span>
    ))
    }
    }
    
    Login or Signup to reply.
  2. Does response.data return the required response, does it contain the array of quote objects?

    I am not sure what you’re trying to do here –

    if (fetchedQuotes) {
    
              const {quote, author} = fetchedQuotes.quotes[0];
            
            setQuoteList(fetchedQuotes.quotes);
            setAuthor(author);
    

    I guess you are trying to set quote here – setQuoteList(quote)?

    Also, you should wrap this part in a condition like so –

    if (fetchedQuotes?.quotes?.length) {
    
              const {quote, author} = fetchedQuotes.quotes[0];
            
            setQuoteList(fetchedQuotes.quotes);
            setAuthor(author);
            } 
            
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search