Question T12457
Visible to All Users

Problems with onComplete

created 2 years ago

Hello,

My first problem is that once I press complete on the survey, there is "Run Survey Again" button. Hence, I decided to make my own. I have a surveyState which is false while the survey is being filled out and true once it is done. However, despite setting the surveyState to true in the onComplete, this does not execute every time. In my code, I only console.log the surveyState after it is set to true. However, first log is false.

CODE:

Code
import React from "react"; import {useState} from "react"; import 'survey-core/defaultV2.min.css'; import { StylesManager, Model } from 'survey-core'; import "survey-core/defaultV2.css"; import { Survey } from 'survey-react-ui'; import { ref, push } from "firebase/database"; import { db } from "../../src/utils/database"; import {surveyJson} from "./surveyJSON"; import Stack from '@mui/material/Stack'; import Button from '@mui/material/Button'; function FotokiteLog(){ const [surveyState, setSurveyState] = useState(false); const query = ref(db, 'Fotokite'); StylesManager.applyTheme("defaultV2"); const survey = new Model(surveyJson); function retakeSurvey() { setSurveyState(false) survey.clear(); survey.render(); } survey.onComplete.add((sender) => { push(query,JSON.stringify(sender.data)) setSurveyState(true) console.log(surveyState) }) return( <div> <Survey model={survey} /> <Stack spacing={2} direction="column"> { surveyState ? <Button variant="contained" size="large" onClick={() => retakeSurvey()}>Log another flight</Button> : null } </Stack> </div> ); } export default FotokiteLog

Answers approved by surveyjs Support

created 2 years ago

Hello Erikvats,
Thank you for sharing the code.

You need to declare a survey constant using the useMemo hook. Now, the survey model so that the survey is not reloaded each time the component is rendered.

JavaScript
const survey = useMemo(() => new Model(json), []); ...

Example.

Please let me know if you have any questions or require further assistance.

    Comments (1)

      Thank you very much! This worked perfectly.

      In several of the examples on the SurveyJS website, there is a "Run Survey Again" button. However, this is not the case when the same code is run in Sandbox. Is it possible to make such a button render automatically once the survey is done?