Is .replace() something different in react v6?

Viewed 1077

I'm doing a meetup app and I want to go back to the main page after the data is submitted, Here is my code:

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

import NewMeetupForm from "../components/meetups/NewMeetupForm";

function NewMeetupsPage() {
  const navigate = useNavigate();

  function addMeetupHandler(meetupData) {
    fetch(
      "https://react-meetup-app-aad0d-default-rtdb.firebaseio.com/meetups.json",
      {
        method: "POST",
        body: JSON.stringify(meetupData),
        headers: {
          "Content-Type": "application.json",
        },
      }
    ).then(() => {
      navigate.replace("/");
    });
  }

  return (
    <section>
      <h1>Add New Meetup</h1>
      <NewMeetupForm onAddMeetup={addMeetupHandler} />
    </section>
  );
}

As you can see I used a

.then(() => {
navigate.replace("/");
});

but when I submit the info, I get this error: Unhandled Rejection (TypeError): navigate.replace is not a function

I know on v6 alotta things have changed, is that the case here or, am I missing something?

2 Answers

in the API documentation the url replacing using navigate is used as follows:

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

  function SignupForm() {
      let navigate = useNavigate();

  async function handleSubmit(event) {
    event.preventDefault();
    await submitForm(event.target);
    navigate("../success", { replace: true });
  }

  return <form onSubmit={handleSubmit}>{/* ... */}</form>;
}

see this line:

navigate("../success", { replace: true });

Further it is stated:

The navigate function has two signatures: Either pass a To value (same type as ) with an optional second { replace, state } arg or Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.

PS: btw I think you are confusing the .replace() with the one from the location method https://developer.mozilla.org/en-US/docs/Web/API/Location/replace

import { useNavigate } from 'react-router-dom';

import NewMeetupForm from '../components/meetups/NewMeetupForm';

const NewMeetupPage = () => {

const navigate = useNavigate();

const addMeetupHandler = (meetupData) => {
    fetch('"https://react-meetup-app-aad0d-default-rtdb.firebaseio.com/meetups.json",
    {
        method: 'POST',
        body: JSON.stringify(meetupData),
        headers: {
            'content-type':'application/json'
        }
    }
    ).then(() => {
        navigate('/', {replace: true})
    });
}
return (
    <section>
       <h1> New Meetup Page</h1>
       <NewMeetupForm   onAddMeetup={addMeetupHandler}/>
    </section>
)

} export default NewMeetupPage

Related