简体   繁体   中英

Why does react app reload after file save in my project?

Hello iI have a project in react + graphql + node and mongod, and iI tried to upload images to a folder in my app and i have a problem with the reload of app after the file save. I tried to manage a local state in the component when performing the upload process, but my local variable changed to the initial state because of a reload app, and cant it does not show a preview of my file. My goal is show a preview of img upload.

I think my problem is in the resolver, in the function storeUpload

Code.

API-----------Resolver------

const Product = require('../models/Product');
const { createWriteStream } = require("fs");

async function createProduct(root, args) {
  console.log(args.file)

  let product = await new Product(args)
  console.log(product);
  product.save()
  if(args.file){
  const { stream, filename, mimetype, encoding } = await args.file;

  await storeUpload({ stream, product });
  }

  return product
 }
 const storeUpload = ({ stream, product }) =>
 new Promise((resolve, reject) =>
  stream
  .pipe(createWriteStream("./images/" + product._id +".png"))
  .on("finish", () => resolve())
  .on("error", reject)
  );

 module.exports = {

 createProduct

 }

---React--- Component----

import React , { useState, useEffect } from 'react'
import {Grid} from '@material-ui/core'
import { Mutation } from "react-apollo"
import {PRODUCTOS} from './Productos'
import gql from "graphql-tag";
import {StyleStateConsumer} from '../../../Context/StylesStateContext'

/** @jsx jsx */
import { jsx, css } from '@emotion/core'

const borde = css({
  borderStyle: 'solid'
})
  const contendorForm = css({
  borderRadius: 15,
  backgroundColor: '#ffffe6'
  },borde)
  const itemsForm = css({
  padding: 15
  })
   const inputStyle = css({
  borderRadius: 5,
  padding: 3
})


const ADD_PRODUCT = gql`
   mutation CreateProduct($title: String, $price: Float, $file: Upload) {
  createProduct(title: $title, price: $price, file: $file) {
 _id
 title
 }
}
 `;

  const CrearProducto = props =>{
  const [titleInput, settitleInput] = useState('')
  const [priceInput, setpriceInput] = useState(0)
  const [fileInput, setfileInput] = useState('')
  const [imgName, setimgName] = useState('default')
  const handleChange = e =>{
        const {name, type, value} = e.target
        if(name === 'titleInput'){settitleInput(value)}
        if(name === 'priceInput'){setpriceInput(parseFloat(value))} 
  }
  const imgUpdate = (imgConxt) => {
        setimgName(imgConxt) 
  }
  useEffect( imgUpdate )
  const handleFile = (obj) =>{console.log(obj)}     
  return(
  <StyleStateConsumer>
        {({imagenID, updateHState})=>(
              <Grid container css={borde}
              direction="row"
              justify="center"
              alignItems="center">
              <Grid item css={contendorForm}>
              {imgUpdate(imagenID)}
                    <Grid container
                    direction="row"
                    justify="center"
                    alignItems="center"><Grid item >Crear Producto:</Grid> 
                    </Grid>
              <Grid container>
              <Mutation mutation={ADD_PRODUCT} refetchQueries={[{
                    query: PRODUCTOS
                    }]}>
                    {(createProduct, { data, loading })=>{
                     if (loading) return <div>Loading...</div>  
                     console.log(data)   
                    return(
                          <div>  
                                <form css={itemsForm} 
                                onSubmit={ (e) => {
                                      e.preventDefault()
                                       createProduct({
                                            variables: {
                                                  title: titleInput,
                                                  price: priceInput,
                                                  file: fileInput
                                            }
                                      })
                                     // 
                                    updateHState(res.data.createProduct._id 
                                     === undefined ? '' : 
                                    res.data.createProduct._id)    
                                      settitleInput('')
                                      setpriceInput(0)

                                     // 
                          console.log(res.data.createProduct._id)
                          }}>
                            <Grid item>
                                <input
                                    css={inputStyle}
                                    type="file"
                                      onChange={({ 
                                            target: { validity, files: 
                                   [file] } }) => validity.valid && 
                              setfileInput(file)
                                      }
                                />
                          </Grid>
                                <Grid item>
                                      <label>
                                            Titulo:
                                      </label>      
                                </Grid>
                                <Grid item>
                                      <input css={inputStyle} type="text" 
                                name="titleInput" 
                                      placeholder="Ingresar Título"
                                      value={titleInput}
                                      onChange={handleChange}
                                      />
                                </Grid>
                                <Grid item>
                                <label>
                                      Precio:
                                </label>      
                                </Grid>
                                <Grid item>
                                      <input css={inputStyle} type="number" 
                                name="priceInput"
                                      placeholder="Ingresar Precio"
                                      value={priceInput}
                                      onChange={handleChange}/>
                                </Grid>
                                <Grid item>
                                      <input type="submit" name="Crear"/>
                                </Grid>
                          </form>

                          </div>       
                    )

                    }}
                    </Mutation>
                    </Grid>

              </Grid>

              <Grid item css={[borde,
                    {
                    backgroundImage:  `url('${require('../../../../../back- 
                    end/images/' + imgName + '.png')}')`,
                    backgroundSize: 'contain',
                    backgroundRepeat: 'no-repeat',
                    height: 300,
                    width: 300}]}>

                    </Grid> 
        </Grid>
        )}
   </StyleStateConsumer>      
   )
   }
  export default CrearProducto

Well, first the imgUpdate function you're passing to useEffect won't ever get its imgConxt parameter. This hook just calls an empty-parameter function to execute a bunch of code after render.

For your main problem, do you have any warnings or errors in the console ? One quick but dirty fix would be to change your <input type='submit'> to type button and do your logic in an onClick handler there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM