Axios with firebase does not return the data while putting it

Viewed 1456

I am making a survey tool with React and Firebase with Axios, right now im trying to make a template feature where I have created a few survey templates which are stored in firebase and now when a user wants to access the template I am able to get the template as json but im not able to duplicate it onto their account as well.

This is the code I am using to get the survey template

const fetchSurvey = async () => {
  const res = await axios.get(
    "/surveys/ckb0kmt3n000e3g5rmjnfw4go/content/questions.json"
  );
  console.log(res.data);
};

where "ckb0kmt3n000e3g5rmjnfw4go" is the survey id, when I do this, the data successfully get logged onto the console, but when I create a new survey using this template:

const fetchSurvey = async () => {
  const res = await axios.get(
    "/surveys/ckb0kmt3n000e3g5rmjnfw4go/content/questions.json"
  );
  return res.data
};
const content = {
  title: "Your Survey Title",
  subTitle: "Your Survey Description",
  creatorDate: new Date(),
  lastModified: new Date(),
  questions: fetchSurvey(),
  submitting: true
};
this.setState({
  _id: newId(),
  content: content,
  userId: this.props.user_Id
});


}



    clickHandler = () => {
        const newSurvey = { ...this.state };
        axios
          .put(
            "/surveys/" + this.state._id + ".json?auth=" + this.props.token,
            newSurvey
          )
          .then(res => {
            this.props.onGetSurveyId(res.data._id);
          })
          .catch(error => {
            console.log(error);
          });
      };

After this, the survey does get created but the questions key will be missing and no questions are rendered.Please help me out

2 Answers
const content = {
  ...
  questions: fetchSurvey(),
  ...
};

this.setState({
  ...
  content: content,
  ...
});

That won't work. questions: fetchSurvey(), evaluates to Promise<any> you have to set state in then callback

componentDidMount() {
  fetchSurvey()
    .then(questions => {
      // either update existing state or create everything there when you get questions
      this.setState(state => ({
        ...state,
        content: {
          ...state.content,
          questions
        }
      }));
  })
}

Related