Home > OS >  save all content clicked into state initial as array
save all content clicked into state initial as array

Time:11-09

i use usestate to create saveImages and setSaveImages, this initial as array, i want to each time i call the function, the content is different, so each time must to push to the array that info, but instead of do push, only replace the 1 position of array, doesnt add new position with different info. I don't know if I explain myself

const galery = useSelector((state) => state.search);
  const dispatch = useDispatch();
  const [saveImages, setSaveImages] = useState([]);

function savePhoto(e) {
    e.preventDefault();
    const { target } = e;
    const content = target.photo.src;
    setSaveImages(content)
    console.log(content)
    localStorage.setItem("img", saveImages);
    dispatch(actionAddFavorite(content));
  }

return(
<section className="w-full gap-0 sm:columns-2 md:columns-3 xl:columns-4 2xl:columns-5 3xl:columns-6">
        {galery.map((item, index) => {
          return (
        

<form onSubmit={savePhoto} key={index} className="relative">
          <button className="bg-gray absolute left-5 top-3 shadow-md">
            Guardar
          </button>
          <img
            name="photo"
            className="object-cover p-2"
            src={item.urls.regular}
            alt={item.alt_description}
          />
        </form>
      );
    })}
  </section>
)

CodePudding user response:

You set your saveImages to contain "content", but what you want is to add "content" to existing saveImages array. Here is how you can do this:

setSaveImages(oldImages => {
  return [...oldImages, content];
});

And here you can learn everything you need to know about state in react

  • Related