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
Try this:
In
db.json
Now you have to change in your
react component
The return statement should be:
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 –
I guess you are trying to set quote here – setQuoteList(quote)?
Also, you should wrap this part in a condition like so –