Passing useState value through parent component using react hooks (getting = undefined)

549 views Asked by At

I'm working in a project already began that's using react class version. I plan to work with react hooks, so to don't refactor all the classes, as I write new codes, I'm trying to mix those react versions (idk if it's a good idea and I should refactor all).

I'm creating a list with pagination and search. The pagination and search are in an unique component.

To this component a need pass the search character value input by user, and here is where I'm facing problem. In other words, I need pass a value to the parent component.

Code is below:

useState hook:

const [search, setSearch] = useState('');

Filter component, that change the search value:

const Filter = () => {
    return (
      <Card>
        <Form.Group label="Filtro">
          <Grid.Row gutters="xs">
            <Grid.Col>
              <Form.Input
                name='search'
                placeholder='Filtro'
                autoFocus
                value={search}
                onChange={e => setSearch(e.target.value)}
              />
            </Grid.Col>
            <Grid.Col auto>
              <Button
                color="success"
                icon="search"
                onClick={filtrar}
              >
              </Button>
            </Grid.Col>
          </Grid.Row>
        </Form.Group>
      </Card>
    );
  }

function getSearchDB() {
    setSearch((search) => {
      return search;
    })
  }

Pagination component, that receive the props:

<Pagination
  baseUrl={'vehicles/toUse'}
  updateState={setStateDB}
  getSearch={getSearchDB}
  fields={'license_plate'}
/>

Printing search value pass through Pagination component:

console.log(this.props.getSearch()) //print undefined

OBS: updateState={setStateDB} is working fine.

Things done to make this work (no success):

  • In getSearch={getSearchDB} directly pass search value. Result: this.props.getSearch() print undefined

  • Defined getSearchDB() to be like:

    function getSearchDB() { return search; }

Result: this.props.getSearch() print undefined.

Is there a way to put it to work?

Guys, let me know if the post is confusion or the English is poorly written.

2

There are 2 answers

4
CertainPerformance On BEST ANSWER

Instead of passing down a function that returns search, why not just pass down search itself as a prop?

<Pagination
  search={search}
const Pagination = (props) => {
  console.log(props.search);
0
Nguyễn Viết Đại On

add :

   <Pagination
   search={search}
/>

In component Pagination :

    const Pagination = ({search}) => {
         console.log(search);
         return {
         //...
         }
     }