Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!