Search code examples
reactjsfilepond

How to pull image name from state for file pond


When I navigate to a particular page I want the file pond image to be repopulated with an image I have already uploaded and the image name is in the database.

Currently I have the image name hardcoded, The image name is available in the state which is set in componentDidMount but the state is being set for file pond as well which is confusing me a bit to be honest.

So, this is when it is hardcoded:

class HomeBannerForm extends InputForm {
  async componentDidMount() {
    const { data: hero } = await getHero();
    this.setState({ data: this.mapToViewModel(hero) });
  }

      state = {
        data: {
          title: "",
          bgImg: ""
        },
        errors: {},
        files: [
          {
            source: "myImage.jpg",
            options: {
              type: "local"
            }
          }
        ]
      };

  mapToViewModel(hero) {
    return {
      id: hero._id,
      title: hero.title,
      bgImg: hero.bgImg
    };
  }

So, I need to change the myImage.jpg to what is in the state from componentDidMount ie: the name from the database. This obviously does not work.

    files: [
      {
        source: this.state.data.bgImg
        options: {
          type: "local"
        }
      }
    ]

Filepond component code:

            <FilePond
              ref={ref => (this.pond = ref)}
              files={this.state.files}
              allowMultiple={false}
              maxFiles={1}
              instantUpload={false}
              name="bgImg"
              server={{
                process: "http://localhost:8000/api/hero/",
                load: "http://localhost:8000/img/"
              }}
              oninit={() => this.handleInit()}
              onupdatefiles={fileItems => {
                // Set currently active file objects to this.state
                this.setState({
                  files: fileItems.map(fileItem => fileItem.file)
                });
              }}
              // callback for successfully uploaded image
              onprocessfile={() => this.uploadComplete()}
            />

Solution

  • Looks like you need to tweak your hero mapping:

    mapToState(hero) {
       return {
         data: {
           title: hero.title,
           bgImg: hero.bgImg
         },
         errors: {},
         files: [
           {
             source: hero.bgImg,
             options: {
               type: "local"
            }
          }
        ]
      };
    }
    async componentDidMount() {
        const { data: hero } = await getHero();
        this.setState(this.mapToState(hero));
    }