DEV Community

hafsahussein
hafsahussein

Posted on

getting image from local storage using react

I am trying to work on a simple image editor using cropperjs and react, I want my project to let the user upload an image crop it and then download it I am using the browser local storage to store the user's image then I am importing the image from local storage to the canvas, if the user does not upload an image I have a default image to let the user play with.
The local storage is storing the user image properly and download is also working for me but my problem is that the local storage image is not coming to canvas and it shows only the default image.

here is my upload form component code

import React from 'react';
const UploadForm = ({uploader}) => {
    const handleChange = (e) =>{
        uploader(e.target.files[0])
    }
    return <form>
        <input type="file" accept ="image/*" onChange ={handleChange}/>
    </form>;
}
export default UploadForm;
Enter fullscreen mode Exit fullscreen mode

and here is my App component code

import React, { useState, useEffect } from 'react';
import Cropper from './comps/cropper.jsx';
import UploadForm from './comps/UploadForm.jsx';
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>
            <UploadForm uploader = {uploader}/>
            <Cropper src ={url}/>
        </div>
     );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

and here is my cropper component code

import React, { Component } from 'react'
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.min.css';
import './cropper.css'
import image from '../image.png';
export class cropper extends Component {
    state= {
        imageDestination:""
    }
    imageElement = React.createRef();
    componentDidMount(){
        const cropper = new Cropper(this.imageElement.current, {
            // zoomable:true,
            scalable:true,
            aspectRatio:1,
            crop:()=>{
                const canvas = cropper.getCroppedCanvas();
                this.setState({
                    imageDestination:canvas.toDataURL('image/png')
                })
            }

        });

    }
    render() {

        return (
            <div>
              <div className ="img-container">
                  <img ref ={this.imageElement} src ={this.props.src||image} alt ="source"/>
                  </div>  
                  <img src = {this.state.imageDestination} className = "img-preview" alt ="Destination" />
                  {this.state.imageDestination&&<a href ={this.state.imageDestination}
                   download>Download</a> 
}
            </div>
        )
    }
}

export default cropper
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
harshilparmar profile image
Harshil Parmar

In you App component code you are fetching recent-image from localstorage only after
first render

 useEffect(() => {
        setUrl(localStorage.getItem('recent-image'));
    }, [])
Enter fullscreen mode Exit fullscreen mode

you should try this

 useEffect(() => {
        setUrl(localStorage.getItem('recent-image'));
    }, [localStorage.getItem('recent-image')])
Enter fullscreen mode Exit fullscreen mode