I use react image slider image slider
The issue is that when i store images paths like it's in code example it works ok
const images = [
{ url: "1.jpg" },
{ url: "2.jpg" }
];
But when i use it image slider does not work
const [imagePath, setImagePath] = useState([]);
const fetchData = async () => {
const images = await (await MessageService.getImagesById(location.state.message)).data; //here i get data from db
const imagesPath = images.map(i => ({url: i.url}))
setImagePath(imagesPath);
console.log(imagesPath);//[ {url: "1.jpg"}, {url: "2.jpg"}]
}
};
useEffect(() => {
fetchData();
});
CodePudding user response:
Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log
right after it, it will likely run before the state has actually finished updating.
You can instead, for example, use a useEffect
hook that is dependant on the relevant state in-order to see that the state value actually gets updates as anticipated.
Example:
useEffect(() => {
console.log(imagePath)
// Whatever else we want to do after the state has been updated.
}, [imagePath])
This console.log
will run only after the state has finished changing and a render has occurred.
- Note: "imagePath" in the example is interchangeable with whatever other state piece you're dealing with.
Check the documentation for more info about this.