skip to Main Content

I am currently working on implementing a redirection to a confirmation page once the submission process becomes successful (i.e., when a boolean flag, onSubmit, turns true). However, I am encountering an error when utilizing the navigation method. My project involves the use of the react-router-dom library.

import React, { useState } from 'react'; // Import useEffect
import axios from 'axios';
import { auth } from './firebase';
import { Link, Routes, Route, Navigate } from 'react-router-dom';
import './mainpage.css';
import './Confirmation';

const Mainpage = () => {
  const apiKey = '******';
  const baseId = '***********';
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phoneNumber: '',
  });

  const [submitted, setSubmitted] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post(
        `https://api.airtable.com/v0/${baseId}/Users`,
        {
          records: [
            {
              fields: {
                name: formData.name,
                email: formData.email,
                phoneNumber: auth.currentUser.phoneNumber,
                address: formData.address,
                ocation: formData.location,
                fssai: formData.fssai,
                ResturantName: formData.ResturantName,
                Password: formData.Password,
              },
            },
          ],
        },
        {
          headers: {
            Authorization: `Bearer ${apiKey}`,
            'Content-Type': 'application/json',
          },
        }
      );

      console.log('Data sent to Airtable:', response.data);
      
      // Handle success, show a confirmation message, or redirect the user.
      setSubmitted(true);
    } catch (error) {
      console.error('Error sending data to Airtable:', error);
      // Handle the error, display an error message to the user, or perform error recovery.
    }  
  };

  if(submitted = true){
    Navigate('./Confermation');
  }

  const logout = () => {
    auth.signOut();
  };

  return (
    <div className="main-container">
      <center>
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="name">Enter your Full Name:</label>
            <input
              ********rest of code
  );
};

export default Mainpage;

2

Answers


  1. Navigate is a React component and must be rendered in order to have any effect. In React we don’t call the component functions directly, they are expressed in terms of JSX and React handles calling them at the right time (e.g. when the component is being rendered to the DOM).

    if (submitted) {
      return <Navigate to="./confermation" />;
    }
    

    Typically though you would just use the useNavigate hook and issue an imperative navigation action directly in the handler.

    Example:

    import React, { useState } from 'react'; // Import useEffect
    import axios from 'axios';
    import { auth } from './firebase';
    import { Link, Routes, Route, useNavigate } from 'react-router-dom';
    import './mainpage.css';
    import './Confirmation';
    
    const Mainpage = () => {
      const navigate = useNavigate();
    
      ...
    
      const handleSubmit = async (e) => {
        e.preventDefault();
    
        try {
          const response = await axios.post(
            ....
          );
    
          console.log('Data sent to Airtable:', response.data);
          
          // Handle success, show a confirmation message, or redirect the user.
          navigate("./confermation"); // <-- imperative navigation
        } catch (error) {
          console.error('Error sending data to Airtable:', error);
          // Handle the error, display an error message to the user, or perform error recovery.
        }   
       
      };
    
      const logout = () => {
        auth.signOut();
      };    
    
      return (
        ....
      );
    };
    
    export default Mainpage;
    
    Login or Signup to reply.
  2. It seems based on the code you shared in your question that the use of the hook provided by react-router-dom called ‘useNavigate’ is what you need.

    this example is pulled from the documentation here

    import { useNavigate } from "react-router-dom";
    
    function useLogoutTimer() {
      const userIsInactive = useFakeInactiveUser();
      const navigate = useNavigate();
    
      useEffect(() => {
        if (userIsInactive) {
          fake.logout();
          navigate("/session-timed-out");
        }
      }, [userIsInactive]);
    }

    this way you can keep your basic setup without needing to change much else (notice how the hook is brought in and then the ‘navigate’ function is extracted and called with a string representing the desired path)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search