7

In my func component I am trying to use history.push in this way:

import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

interface Props {
  question: Question;
  selectedAnswer: SelectedOption | undefined;
}

const LastScreen: React.FC<Props> = (props: Props) => {
  const history = useHistory();
  ...
  
  useEffect(() => {
    if (progress === 100) {
      const id = uuid();
      history.push({
        pathname: `/p/${id}`,
        state: { userAnswers },
      });
    }
  }, [progress, userAnswers, history]);
  ...
};

but it gives an error:

Argument of type '{ pathname: string; state: { userAnswers: UserAnswers | undefined; }; }' is not assignable to parameter of type 'To'. Object literal may only specify known properties, and 'state' does not exist in type 'PartialPath'.ts(2345)

How to fix it?

Aleks Barylo
  • 131
  • 1
  • 2
  • 4
  • after trying to fix it I found the problem appears when using custom history, like ```import history from 'history';``` and then ```...``` So when I replaced it with ```...``` the problem disappeared. – Aleks Barylo Jul 09 '20 at 09:35
  • Note: `useHistory` is old (v5), now (v6), `const navigate = useNavigate(); navigate('/')` is used. Reference: https://stackoverflow.com/a/70274942/6702598 – DarkTrick Jun 22 '22 at 03:26

2 Answers2

0

The useHistory hook gives you access to the history instance that you may use to navigate.

import { useHistory } from "react-router-dom";
  

let history = useHistory();
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vipin N
  • 23
  • 6
0

The react-router documentation says the following on the history.push function:

push(path, [state]) - (function) Pushes a new entry onto the history stack

I'm not sure what variable type userHistory is, but it needs to be a state variable. I can tell it isn't because you aren't importing useState. Import useState with useEffect like this:

import React, { useEffect, useState } from 'react';

And declare the variable like this:

const [ userHistory, setUserHistory ] = useState();

Then you can set userHistory:

setUserHistory("foo");

Sources:

React Router history doucmentation

ReactJS useState documentation

steven s
  • 11
  • 4