/
var
/
www
/
html
/
cravings
/
resources
/
components
/
HOC
/
Upload File
HOME
import React, { useEffect, useState } from 'react'; import { useHistory, useParams } from 'react-router-dom'; function questionWrapper(WrappedComponent, data) { return function(props) { let [formValues, setFormValues] = useState({}); let [loading, setLoading] = useState(false); let history = useHistory(); let params = useParams(); useEffect(() => { setLoading(true) // TODO: fetch previous answers props.select() // const nextQuestion = props.next(); fetch(`/test/answers/${props.current}`) .then(response => response.json()) .then(answers => { if(answers) setFormValues(answers) setLoading(false) }); }, []); const handleNextQuestion = (e, next) => { // console.log('hello') e.preventDefault(); // setLoading(true) const nextQuestion = next === 'prev' ? props.prev() : props.next(); if(nextQuestion) { handleSubmit().then(res => { history.push(`/test/start/${nextQuestion}`) // setLoading(false) }).catch(error => console.log(error)) } } const postAnswer = (e) => { handleSubmit(); } const handleSubmit = () => { // const nextQuestion = props.next(); return fetch(`/test/answers/${props.current}`, {credentials: 'same-origin', method: 'POST', body: JSON.stringify(formValues)}) .then(response => response.json()) } const handleChange = (e) => { console.log('changing') setFormValues({...formValues, [e.target.name]: e.target.value}) } let response = loading ? <div style={styles.loading}>Loading</div> : <WrappedComponent {...props} next={handleNextQuestion} inputs={formValues} handleChange={handleChange} postAnswer={postAnswer} />; return response; } } export default questionWrapper; const styles = { loading: { position: 'fixed', right: 0, top: 0, bottom: 0, left: 0, display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 1000, backgroundColor: '#fff' } }