Home > database >  How to create an array of objects in react?
How to create an array of objects in react?

Time:03-17

I am new to the react world. I am trying to write a code in which when an icon is pressed the Image is added into a favourite category and then on the favourite page the image should be displayed. I am having an issue with not knowing how to dynamically get the value out of the image and add them to favourite category without loosing the pervious value. I think the way I wrote states seems messed up. I write in typescript and use material UI

SearchResults

const [images, setImages] = useState([]);
const [favImage, setFavImage] = useState<ImageProps>({
    id: '',
    farm: 0,
    server: '',
    secret: '',
    title: ''
});

const handleFavImage = ({ farm, server, id, secret, title }: ImageProps): void => {
    setFavImage({ id, farm, server, secret, title });
};

ImageModal

const handleFavourite = (): void => {
    setIcon(!icon);
    if (!icon === true && handleFavImage !== undefined) {
        handleFavImage({ farm, server, id, secret, title });
    }
};

CodePudding user response:

Use Image Id as reference.

Use redux store / local storage to store the fav image Ids.

Assuming you have all the images here:

const [images, setImages] = useState([]);

On click of the Icon, pass Image Id of the selected Image and iterate through the images array to find the image props.

just to make you understand how to use the component state array do to this operation:

Lets create a state which will store fav image ids

const [favImages, setFavImages] = useState([]);

On Click will look something like this

const handleOnClick = (imageId) => {
    var arr = [...favImages]; //copy array by value
    arr.push(imageId)
    setFavImages(arr) //override state with new values
}

Now the favImages array has the list of fav image ids.

Now, use this favImages in your favourite page component.

let favImageProps = props.images.filter(image => props.favImages.indexOf(image.id) !== -1)

CodePudding user response:

I had the restriction for not using var and let in the code. So I had to change the code.

    const [images, setImages] = useState([]);
    const [favImage, setFavImage] = useState<ImageProps[]>([]);
    const handleFavImage = ({ farm, server, id, secret, title }: ImageProps): void => {
        setFavImage([...favImage, { id, farm, server, secret, title }]);
    };
  • Related