DEV Community

hafsahussein
hafsahussein

Posted on

2 4

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

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

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay