3

I want to upload image and save it in local stage,in react js, but it works after first rerender, when I upload image it is not shown before refresh

    const App = () => {
    const [url, setUrl] =useState('');
        const uploader = (file) =>{
        const reader = new FileReader();
        reader.addEventListener('load', ()=>{
            localStorage.setItem('recent-image',reader.result)
        })
        reader.readAsDataURL(file);
    }
    useEffect(() => {
        setUrl(localStorage.getItem('recent-image'));
    }, [])
    return ( 
        <div>
            
            <img src ={url}/>
        </div>
     );
   }
1
  • Show your code. Commented Feb 10, 2023 at 21:57

1 Answer 1

1

Try adding "setUrl(localStorage.getItem('recent-image'));" to the logic in your event listener callback. React re-renders components when state is updated, so you need to change state to see the newly uploaded image.

reader.addEventListener('load', ()=>{
        localStorage.setItem('recent-image',reader.result)
        setUrl(localStorage.getItem('recent-image'));
})
Sign up to request clarification or add additional context in comments.

1 Comment

it works, I do not believe thank u so much, u saved my life

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.