Fill the field immediately after reloading the page

Viewed 441

I have search page in my NextJS application. URL example - /search?q=Naaarutoo. And for example after reloading I just want to set "Naaarutoo" as the input value (I know how to set query param to input value) IMMEDIATELY.

If we look closer we will see that field didn't fulfilled:

enter image description here

I think this is because the server side returns simple HTML to client and only after that starts client side execution. Correct me if I'm wrong.

import React from 'react'
import {Formik, Form, Field} from 'formik'

const Search = ({router: {query}}) => (
  <Formik enableReinitialize onSubmit={() => {

  }} initialValues={{q: query.q || ''}} render={() => (
    <Form>
      <Field name='q' type="search" placeholder="Find something"/>
    </Form>
  )}/>
)

export default withPageRouter(Search)

Last update:

I don't know why but it works (I don't remember what I did ( ͡° ͜ʖ ͡°) ), ok, thanks all for your help.

1 Answers

You need getInitialProps to use query

import React from 'react'
import { Formik, Form, Field } from 'formik'

const Search = ({ query }) => (
    <Formik onSubmit={() => { }} initialValues={{ q: query.q || '' }} render={() => (
        <Form>
            <Field name='q' type="search" placeholder="Find something" />
        </Form>
    )} />
)

Search.getInitialProps = ({ query }) => {
    return { query }
}

export default Search

I checked it and it works fine for me.

Related