简体   繁体   中英

How to refetch data without refreshing the page in React graphql

I am a newbie here. In the below code I have used React + React-Apollo.

I am uploading image and retrieving the images from db using Graphql and displaying it in a table

So the problem is when I upload the image it is not getting displayed until I refresh the page. I need the images to be displayed when I click upload button. Please see the code below

Component Code:

import React from 'react'
import axios from 'axios';
import gql from 'graphql-tag';
import {Query} from 'react-apollo';

const GET_FILES = gql`
    query getFiles{
        getFiles{
            id 
            image
            
        }
    }`;

class ImageContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            file: null
        };
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }
    onFormSubmit = (e) =>{
        e.preventDefault();
        const formData = new FormData();
        formData.append('myImage',this.state.file);
        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        };
        axios.post("http://localhost:4000/upload",formData,config)
            .then((response) => {
                alert("The file is successfully uploaded");
                console.log(response.data.filename)
                console.log(response.data.destination)
                window.location.reload();
                this.setState({file: response.data.filename})
            }).catch((error) => {
        });
    }
    onChange = (e) => {
        this.setState({file:e.target.files[0]});
    }
    
    render() {
        return (
            <React.Fragment>
                <div className = "container">
            <form onSubmit = {this.onFormSubmit}>
                <h1>File Upload</h1>
                <input type = "file" name = "myImage" onChange = {this.onChange} />
                <button type = "submit">Upload</button>
            </form>
            <div>
            <Query query = {GET_FILES}>
                {({loading,error,data}) => {
                    if (loading) return <h4>Loading..</h4>;
                    if (error) console.log(error);
                    console.log(data)
                    return (
                        
                        <React.Fragment>
                            <div className = "row mt-3">
                                <div className = "col">
                                    <table className = "table table-striped table-primary bg-dark text-white text-center">
                                        <thead>
                                        <tr>
                                            <th>Image</th>
                                            <th></th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        
                                            {
                                         data.getFiles.map(file => {
                                             return(
                                                <React.Fragment>
                                                <tr key = {file.id}>
                                             <tr>{file.image}</tr>
                                                 <td><img src = {`http://localhost:4000/${file.image}`} alt = ""/></td>
                                            
                                                 </tr>
                                                 </React.Fragment>
                                             )
                                         
                                            })
                                        }
                                        </tbody>

                                    </table>
                                </div>
                            </div>
                            
                        </React.Fragment>
                    )
                }}

            </Query>
            </div>
        </div>
    </React.Fragment>
        )
    }
}

export default ImageContainer

You can use refetch provided as Query Component props

import React from 'react'
import axios from 'axios';
import gql from 'graphql-tag';
import {Query} from 'react-apollo';

const GET_FILES = gql`
  query getFiles {
      getFiles{
          id
          image
      }
  }
`;

class ImageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            file: null
        };
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onFormSubmit = (evt) => {
        evt.preventDefault();
        const formData = new FormData();
        formData.append('myImage',this.state.file);

        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        };

        axios.post("http://localhost:4000/upload", formData, config)
            .then((response) => {
                alert("The file is successfully uploaded");
                console.log(response.data.filename)
                console.log(response.data.destination)
                window.location.reload();
                this.setState({
                  file: response.data.filename
                }, () => {
                  this.query_refetch && this.query_refetch(); // refetch function called
                })
            }).catch((error) => {
        });
    }
    onChange = (e) => {
        this.setState({file:e.target.files[0]});
    }

    render() {
        return (
            <React.Fragment>
                <div className = "container">
                    <form onSubmit = {this.onFormSubmit}>
                        <h1>File Upload</h1>
                        <input type = "file" name = "myImage" onChange = {this.onChange} />
                        <button type = "submit">Upload</button>
                    </form>
                    <div>
                      <Query query={GET_FILES}>
                          {({loading, error, data, refetch}) => {

                              this.query_refetch = refetch; // refetch function assigned

                              if (loading) return <h4>Loading..</h4>;
                              if (error) console.log(error);
                              console.log(data)
                              return (
                                  <React.Fragment>
                                      <div className = "row mt-3">
                                          <div className = "col">
                                              <table className = "table table-striped table-primary bg-dark text-white text-center">
                                                  <thead>
                                                      <tr>
                                                          <th>Image</th>
                                                          <th></th>
                                                      </tr>
                                                  </thead>
                                                  <tbody>
                                                    {data.getFiles.map(file => {
                                                      return (
                                                        <React.Fragment>
                                                            <tr key = {file.id}>
                                                            <tr>{file.image}</tr>
                                                              <td>
                                                                  <img src = {`http://localhost:4000/${file.image}`} alt=""/>
                                                              </td>
                                                            </tr>
                                                        </React.Fragment>
                                                      );
                                                    })}
                                                  </tbody>
                                              </table>
                                          </div>
                                      </div>
                                  </React.Fragment>
                              )
                          }}
                      </Query>
                  </div>
              </div>
          </React.Fragment>
        )
    }
}

export default ImageContainer

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