Hello I am working on a personal project and I can’t seem to add an array of data that I am fetching from the backend to a useState array I can see the array but when I try to update it using the useState setter function it doesn’t work or show no update at all.
I am feeling so dumb on this and have been stuck for around 3 hrs.
I am attaching my react code and a screenshot of the Google Chrome inspection tool. Please mention if you need more code I will try to provide as much as possible.
Thank you.
import { useEffect, useState } from "react";
import axios from "axios";
import toast from "react-hot-toast";
const UseGetconversation = async () => {
const [loading, setloading] = useState(false);
const [Conversations, setConversations] = useState([]);
useEffect(() => {
const getconversation = async () => {
setloading(true);
try {
const res = await axios.get("api/users/");
if (res.error) {
throw new Error(res.error);
}
const data = res.data;
console.log(data);
console.log(Array.isArray(data));
setConversations(data);
console.log(Conversations);
} catch (error) {
toast.error(error.message);
} finally {
setloading(false);
}
};
getconversation();
}, []);
return { loading, Conversations };
};
export default UseGetconversation;
2
Answers
Let’s focus on the main part of the code, I am considering that your respective BE is returning an array as res.data nothing else like an object.
console.log(data);
console.log(Array.isArray(data));
I assume that these consoles return you with array data and true.
So when you try to set a array in state, directly dumping doesn’t helps
Write it like this
Always use the spread operator to set state, it will work as expected.
And one more thing to add beyond your scope as a tip
console.log(Conversations);
You are trying to print the Conversations state just after setting it. state setting is async so that it will console an empty array. As Js will not wait until the state is set. It will execute the next line. If you want to console or see the data that is set use callbacks. This means console after data is set.
If you want to check the conversation array pale the consolelog outside the useEffect, bcz setState a async function.