sultan
sultan

Reputation: 419

(0 , _reactRouterDom.useHistory) is not a function

I'm using react-router-dom v6.0.0-beta.0 with reac-redux 7.2.2 and want to edit the state value by using the useState hook, but when I click on EditIcon it gives me this error...

(0 , _reactRouterDom.useHistory) is not a function

EditTodo.js

import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import { useParams } from "react-router-dom";

import { todoUpdated } from "./TodoSlice";

export const EditTodo = () => {
  const { todoId } = useParams();

  const todo = useSelector((state) =>
    state.todo.find((todo) => todo.id === todoId)
  );

  const [name, setName] = useState();
  const [description, setDescription] = useState();

  const dispatch = useDispatch();
  const history = useHistory();

  const onTitleChanged = (e) => setName(e.target.value);
  const onContentChanged = (e) => setDescription(e.target.value);

  const onSavePostClicked = () => {
    if (name && description) {
      dispatch(todoUpdated({ id: todoId, name, description }));
      history.push(`/todo/${todoId}`);
    }
  };

  return todo ? (
    <section>
      <h2>Edit Post</h2>
      <form>
        <label htmlFor="postTitle">Post Title:</label>
        <input
          type="text"
          id="postTitle"
          name="postTitle"
          placeholder="What's on your mind?"
          value={name}
          onChange={onTitleChanged}
        />
        <label htmlFor="postContent">Content:</label>
        <textarea
          id="postContent"
          name="postContent"
          value={description}
          onChange={onContentChanged}
        />
      </form>
      <button type="button" onClick={onSavePostClicked}>
        Save Post
      </button>
    </section>
  ) : null;
};

How to fix this issue? if someone knows help me to solve this. thanks here is the codesandbox

Upvotes: 13

Views: 23123

Answers (2)

NAUMAN IFTIKHAR SATTI
NAUMAN IFTIKHAR SATTI

Reputation: 11

It may be due to the fact that you are using react-router-dom V6. in V6 useNavigate is used instead of useHistory.

Step 1: Uninstall react-router-dom: npm uninstall react-router-dom.

Step 2: install v5.3: npm install [email protected]

You are good to go now.

Upvotes: 1

Benjamin
Benjamin

Reputation: 3656

You are using the beta version of react-router-dom. In v6, useHistory is replaced by useNavigate

https://dev.to/zenveus/routing-with-react-router-v6-6b1

If you want to use useHistory you should install v5 instead.

const navigate = useNavigate();

const onSavePostClicked = () => {
  if (name && description) {
    dispatch(todoUpdated({ id: todoId, name, description }));
    navigate(`/todo/${todoId}`);
  }
};

Upvotes: 25

Related Questions