I have a list of object stored in a state called itemsToUpload. There's a button to upload the list of objects to a database. The following is an object in the list.
{
type:"Fiat",
model:"500",
color:"white",
imgUrl="https://latestlyhunt.com/wp-content/uploads/2021/03/Fiat-made-a-%E2%80%98Hey-Google-car.jpg"
};
When sending the data to the database, I want to make the imgUrl to null.
The following code is how I set the imgUrl to null.
const submitHandler =async()=>{
setitemsToUpload((items)=>
items.map((item)=>({
...item,
imgUrl:null
})))
const response =await axios.post("api url",itemsToUpload)
console.log(response )
}
After making the imgUrl to null,itemsToUpload state changes but the data sending to the API states that imgUrl is not null
What is the issue here?
Array.map doesn't modify the array, it creates a new array with the returns value, so you need to assign the result of your map to the array
const items = [
{
type:"Fiat",
model:"500",
color:"white",
imgUrl:"https://latestlyhunt.com/wp-content/uploads/2021/03/Fiat-made-a-%E2%80%98Hey-Google-car.jpg"
}
]
const modifiedItems = items.map((item)=>({
...item,
imgUrl:null
}))
console.log(items)
console.log(modifiedItems)
The code is working here. So I'm not sure if the problem belongs with this part.
const array = [{
type:"Fiat",
model:"500",
color:"white",
imgUrl:"https://latestlyhunt.com/wp-content/uploads/2021/03/Fiat-made-a-%E2%80%98Hey-Google-car.jpg"
},
{
type:"Fiat",
model:"500",
color:"white",
imgUrl:"https://latestlyhunt.com/wp-content/uploads/2021/03/Fiat-made-a-%E2%80%98Hey-Google-car.jpg"
},
{
type:"Fiat",
model:"500",
color:"white",
imgUrl:"https://latestlyhunt.com/wp-content/uploads/2021/03/Fiat-made-a-%E2%80%98Hey-Google-car.jpg"
}];
console.log(array);
const clearIt = array => {
return array.map(item => {
item.imgUrl = null
return item;
});
};
const newArray = clearIt(array);
console.log(newArray);
In your code setitemsToUpload does not immediately mutates the itemsToUpload but rather tells React to schedule a state update and rerender, while submitHandler continues to run and calls axios.post before itemsToUpload is updated.
Try to refactor it like this:
const submitHandler = async () => {
const newItemsToUpload = items.map((item) => ({
...item,
imgUrl: null
}))
setitemsToUpload((items) => newItemsToUpload)
const response = await axios.post("api url", newItemsToUpload)
console.log(response)
}