Next.js not updating state during OnClick after router.push to same page with different ID

18 views Asked by At

I have a page similar to this:

File: [pid].tsx

type ProblemPageProps = {
    problem: Problem
};

const ProblemPage:React.FC<ProblemPageProps> = ({problem}) => {
    ...

    return (
        <div>
            <Workspace problem={problem} />
        </div>
    );
}
export default ProblemPage;

export async function getStaticPaths() {
    const paths = Object.keys(problems).map((key) => ({
        params: {pid:key}
    }))

    return {
        paths,
        fallback: false
    }
}

export async function getStaticProps({params}: {params: {pid: string}}) {
    const {pid} = params;
    const problem = problems[pid];

    if (!problem) {
        return {
            notFound: true
        }
    }

    return {
        props: {
            problem
        }
    }
}

In Workspace I have something like this - gets triggered on a click of a button:

const handleCodeReset = () => {
    setUserCode(problem.starterCode);
};

And I have one function to push to the same [pid].tsx page but with a different PID:

const handlePreviousProblemChange = () => {
    router.push(`/problems/my_second_problem`);
}

Being triggered by:

<div onClick={() => handlePreviousProblemChange()}>
    BLA BLA BLA
</div>

When that happens, problem is pointing to my_second_problem which is exactly what I need but during onClick event, problem.starterCode still points to the previous pid. What can I do to make sure problem.startedCode gets referenced in the right way?

This is an example of problem:

interface ProblemMap {
    [key: string]: Problem;
}

export const problems: ProblemMap = {
    "key": value,
    ...
}
0

There are 0 answers