skip to Main Content

I am building an react app and want to save multiple photos to firestore to do that i want to take their url in imageurl: [] an array to save them in firestore.

      const [data, setData] = useState({

      name: "",
      phone: "",
      location: "",
      imageurl:[],

   })

here every data is saving and working fine name,phone,location but the problem is with array value imageurl[] they are not saving

i m saving urls like

            setData((prev)=> {

              return {

                ...prev, [data.imageurl] : [...data.imageurl , url]
              }
            })
           })

it is not working.

i am new to react please guide me how can i solve this problem. thank you

3

Answers


  1. Try with this:

    const [data, setData] = useState({
      name: "",
      phone: "",
      location: "",
      imageurl: [],
    });
    
    // Function to add a URL to the imageurl array
    const addImageUrl = (url) => {
      setData((prevData) => ({
        ...prevData,
        imageurl: [...prevData.imageurl, url],
      }));
    };
    
    // Example usage
    const handleImageUpload = (url) => {
      // Assuming you have obtained the URL from somewhere
      addImageUrl(url);
    };
    

    You can then call addImageUrl(url) whenever you want to add a URL to the imageurl array. For example, you might call it inside an event handler that handles image uploads.

    Login or Signup to reply.
  2. In the setData when creating the return object you have put the value as key, when you set the key as [data.imageurl]. also don’t use the data variable inside setData, use the prev variable supplied by the function

    try this code

    setData((prev) => {
       return {
          ...prev,
          imageurl: [...prev.imageurl, url],
      };
    });
    
    Login or Signup to reply.
  3. You can tried like this also:

        setData((prevState) => ({
      ...prevState,
      imageurl: [...prevState.imageurl, url]
    }));
    

    The code updates the imageurl property in the component’s state by creating a new state object that’s a copy of the previous state and appends a new URL to the imageurl array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search