'Update state from another component

I am trying to update state of page index in index.js from component Pagination,

my index.js:

import useSWR from 'swr';
import { useState } from 'react';

const Index = ({ data }) => {
    
    const initialStatePage = () => 1;

    const [pageIndex, setPageIndex] = useState(initialStatePage);

    const { data } = useSWR(`http://1.2.3.4/api/console?pagination[page]=${pageIndex}`, fetcher, {fallbackData: data});

  return (
<>
    <h1> {data} <h1/>
    <Pagination pagenow={initialStatePage}/>
<>
  );
};
export default Index;

my component:

import { useState } from 'react';

const Pagination = ({ pagenow }) => {
    const [pageIndex, setPageIndex] = useState(pagenow);
  return (
    <>
                    <li>
                      <button onClick={() => setPageIndex(pageIndex - 1)}>
                      </button>
                    </li>
                      <button onClick={() => setPageIndex(pageIndex + 1)}>
                      </button>
                    </li>
    </>
    )
};

export default Pagination;

but after click, page index is not updating from my component



Solution 1:[1]

The state in your Pagination component will rerender the children element, not the whole page. If you want it to rerender the whole Index page, pass your setPageIndex function to the component and use it to set the page index:

index.js

import useSWR from 'swr';
import { useState } from 'react';

const Index = ({ data }) => {
    const initialStatePage = () => 1;

    const [pageIndex, setPageIndex] = useState(initialStatePage);
    const { data } = useSWR(`http://1.2.3.4/api/console?pagination[page]=${pageIndex}`, fetcher, {fallbackData: data});

    return <>
        <h1>{data}</h1>
        <Pagination pagenow={initialStatePage} setPageIndex={setPageIndex} />
    <>;
};
export default Index;

Pagination component file

import { useState } from 'react';

const Pagination = ({ pagenow: pageIndex, setPageIndex }) => {
    return <>
        <li>
            <button onClick={() => setPageIndex(pageIndex - 1)}></button>
            <button onClick={() => setPageIndex(pageIndex + 1)}></button>
        </li>
    </>;
};

export default Pagination;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AquaPI