C
C
cyberlain2022-02-15 07:33:28
React
cyberlain, 2022-02-15 07:33:28

React Query - how to clear a form on successful form submission?

I made a form and screwed Formik

<form onSubmit={formik.handleSubmit}>
<input id="chapter" onChange={formik.handleChange} type="text" placeholder="Раздел" required />
***
<button>Сохранить</button>
</form>


Saving data from form happens inside React Query mutation
const mutation = useMutation((item) =>
        axios({
          method: "POST",
          url: "https://api.***",
          data: item
        })
    );


Question to those present - what needs to be written inside
if (mutation.isSuccess){

    }

to clear the form? formik.resetForm() doesn't work and throws an error on the screen

620b2d165cbe7628015092.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mesuti, 2022-02-15
@cyberlain

+1 вариант

const input = useRef(null)
...
function successSubmit() {
   input.current.value = ""
}
...
<Input ref={input } />

+2 вариант через state
const [state, setState] = useState({
   inputValue: ''
})
...
function successSubmit() {
   setState(prevState => {
        return {
            ...prevState,
            inputValue: ''
        }
    })
}
...
<Input 
   value={state.inputValue} 
   onInput={e => {
    setState(prevState => {
        return {
            ...prevState,
            inputValue: e.target.value
        }
    })
   }}/>

+3 Вариант изощренный - "до лучших времен"
function successSubmit() {
   document.querySelectorAll('input').forEach(i => i.value = '')
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question