0

Lets say you have a react component that shows image, at first you pass default src as props to this component. In that component You have the functionality that you can search and and change these images src dynamically. Now the changes images src or new image src is stored in the local storage of the browser.

The question is if I have 'n' no of this components how do I save their new src in the local storage in the following format

Image : [{id:1, src:"First image src"}, {id:2,src: "second image src"},...] and so on.

This is basically saving the n no of image and their corresponding id and their src together so that whichever image we change we can persist only that image and not the others.

My component

import React, { useState,useEffect } from "react";
import "./giffer.css";
import {GoSearch} from "react-icons/go";
const GIPHY_API = "https://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&limit=20&offset=0&q=";

let GifSearch = ({src,id}) =>{

    let [search, setSearch]  = useState("");
    let [gifs,setGifs]         = useState([]);
    let [updatedGif,setUpdatedGif] = useState("");
    // let [storedGif,setStoredGif ]  = useState([]);
    let [loading,setLoading] = useState(false); 

  console.log(id,src)

    let searchGif =()=>{
        if(search.length >0){
            setLoading(true);

            fetch(GIPHY_API+search)
            .then((res)=>{
                setLoading(false);
                return res.json();
            })
            .then((result)=>{
                setSearch("")
                setGifs(result.data.map((gif)=>{
                    // console.log(gif.images.fixed_height.url)
                    return gif.images.fixed_height.url;
                }))
            })
            .catch((err)=>{
                console.log(err);
            })
        }
        else if(search.length===0)
        {
            console.log("Search your Gif");  
        }

    }

    let setNewGif = (gif)=>{
        setUpdatedGif(gif);
        setSearch("")
        setGifs([]);
    }

    useEffect(()=>{
        const localStorageGif = localStorage.getItem('Gif');
        if(localStorageGif){
            setUpdatedGif(JSON.parse(localStorageGif))
        } 
    },[])

    useEffect(()=>{
        
            localStorage.setItem('Gif', JSON.stringify(updatedGif));
    
    })

    // console.log(updatedGif)
    
    
    return (
        
        <div>
        <div className="content">
            <div className="searchBox">        
                <input 
                    className="search-input"
                    type="text" 
                    placeholder="Search Gif" 
                    aria-label="Serach Gif"
                    value={search}
                    required
                    onChange={(e)=>setSearch(e.target.value)}
                />
                <button className="search-btn" onClick={searchGif}><GoSearch/></button>
            </div>
            <div key={id} >
                <img  className={"md:h-14 w-1/4 m-0 2xl:h-96 rounded-md shadow-lg object-cover temp-gif"}  src={ updatedGif===""? src : updatedGif } alt="gif" />
            </div>
        </div>

         <div className="result">
         { loading? (
            <div className="loading">
               <div className="loader"/>  
            </div>  
         ) : (
            <div className="list">
             {gifs.map((gif,index)=>{
                 return (
                     <div className="item" key={index}>
                        <img src={gif} onClick={()=>setNewGif(gif)} alt="gif" />
                        <button className="set-btn" onClick={()=>setNewGif(gif)}>Set</button>
                     </div>

                 );
               }) }
            </div>
         )}
         </div>
        </div>    
    );
}

export default GifSearch

My app.js

<div className="flex bg-black p-5 md:space-x-4 space-x-4 md:px-4 ">
        <GifSearch id={1} src={"https://media.giphy.com/media/OW9VxMWPhDHLaaoPiu/giphy.gif"}/>
        <GifSearch id={2} src={"https://media.giphy.com/media/vhLd0wAyLuOkoVHY8T/giphy-downsized-large.gif"}/>
        <GifSearch id={3} src={"https://media.giphy.com/media/ho0xXatV7b3Fo1ZRXN/giphy.gif"}/>
        <GifSearch id={4} src={"https://media.giphy.com/media/zcTrGn54lOrlOABRDB/giphy.gif"}/> 
     </div>

If I try to change the src of the 2/3/4 image then the changed src is shown in the first image. I know that I am not providing sufficient info to save it for that particular image. Any Ideas?

Ardent10
  • 1
  • 1
  • I didn't look at your code but saving an array or object in localstorage is trivial: `localStorage.setItem("myArray", JSON.stringify(myArray));` reading it back is just as trivial: `const myArray = JSON.parse(localStorage.getItem("myArray") || "[]")` (also: asked and answered, please do research before posting a question) – ChrisG Feb 19 '22 at 12:24

0 Answers0