Hello I have a component as follows I'm using usestate hook to initialize the myFeeds variabele to the feeds array and I'm running an effect to add any data from server (socket.io) However when I'm console logging the result myFeeds is giving me an empty array what could be the possible reasons?
const Dashboard = ({feeds}) => {
useEffect(() => {
getFeeds(); // this fetches feeds array
}, []);
const [myFeeds, setMyFeeds] = useState(feeds);
// useEffect hook to get real time messages and add it to feed
useEffect(() => {
let mount = true;
io.on('created' (data) => {
if(mount) {
data && setMyFeeds([...feeds, data]);
}
}
}, [])
console.log(feeds); // gives array of objects
console.log(myFeeds); // giving empty array
return(
<FeedBody body={myFeeds} />
);
}
// mapstatetoprops here
getFeeds is an action creator which is as follows
export const getFeeds = () => async dispatch => {
const res = await axios.get('/feeds');
// dispatch type get feeds here set payload to result of above operation
}
[<>]toolbar button). Stack Snippets support React, including JSX; here's how to do one. You'll have to usesetTimeoutto simulate theio.on()stuff, but otherwise it should be possible to replicate this in a Stack Snippet.getFeeds?getFeedsfunction?feedsis being received by the parent component as a result of an async operation, I think you need to have anotheruseEffecthook to monitor change inprops.feedsand set the state there.if(feeds) setMyFeeds(feeds)and the initial state of myFeeds can be an empty array.