Home > OS >  How to transfer data between React pages?
How to transfer data between React pages?

Time:01-06

I want to pass the states into a object, because after I'll post an API. How can I store the states into the object? If I call the function setAll() causes a infinite loop. Like an example the console.log returns infinite times in the console.

import React,{useState} from 'react';
import Signup1 from '../pages/Signup/steps/Signup1';
import Signup2 from '../pages/Signup/steps/Signup2';
import Signup3 from '../pages/Signup/steps/Signup3';

function Forms() {
  const [alert,setAlert]=useState();
  const [page,setPage] = useState(0);
  const [formData,setFormData]= useState({
    email :"",
    FirstName:"",
    LastName:"",
    CountryNumber:"",
    Number:"",
    JobTitle:"",
    People:"",
    Company:"",
    TaxID:""
    
  })
  

  
  const [email,setEmail] = useState("");
  const [firstName,setFirstName] = useState("");
  const [lastName,setLastName] = useState("");
  const [countryNumber,setCountryNumber] = useState("");
  const [number,setNumber] = useState("");
  const [jobTitle,setJobTitle] = useState("");
  const [people,setPeople] = useState("");
  const [company,setCompany] = useState("");
  const [taxID,setTaxID] = useState("");
  
      
      
      
   const setAll = ()=>{
    setFormData({
      email :email,
      FirstName:firstName,
      LastName:lastName,
      CountryNumber:countryNumber,
      Number:number,
      JobTitle:jobTitle,
      People:people,
      Company:company,
      TaxID:taxID
    })
    console.log(formData)
   } 
   



  

  const PageDisplay = () =>{
    if(page===0){
      
      return <Signup1 
      email={email} 
      setEmail={setEmail} 
      setPage={setPage}
      
      />;
    }
    if(page===1){
      
      return <Signup2 
      firstName={firstName}
      setFirstName={setFirstName}
      lastName={lastName}
      setLastName={setLastName}
      countryNumber={countryNumber}
      setCountryNumber={setCountryNumber}
      number={number}
      setNumber={setNumber}
      jobTitle={jobTitle}
      setJobTitle={setJobTitle} 
      setPage={setPage}/>;
    }
    if(page===2){
      
      return <Signup3
      people={people}
      setPeople={setPeople}
      company={company}
      setCompany={setCompany}
      taxID={taxID}
      setTaxID={setTaxID}
      page={page}
      setPage={setPage}
      />
    
  }
    if(page===3){
      
      return( <div>sucess</div>)
    }
    
}
  /*
    if(page===3){
      
      setAll()
      return<div>sucess</div>
    }
    */
  return (
        <div className='Forms'>
          {PageDisplay()}
        </div> 
      );
}

export default Forms;

CodePudding user response:

Don't call setAll() like this, functions that set state like this should be called on the occurrence of an event (like an onClick) or in a useEffect, whenever you set a state in the component body, the component re-renders which triggers another state set, thus causing an infinite loop, in your case, it's better to set the form body when you call the API. Setting states is a costly operation, so it's better to set form body state finally when you are going to hit the API.

CodePudding user response:

Making a working example always helps someone to create a better and more precise answer to your question. This is how you set your data. Also if you want to send this data to another component/function you can do it by passing formData object, you don't need to set it one by one. Please try to ask any questions you may have.

To see the document clearly, expand the snippet to fill the entire page.

const {useEffect, useState} = React;

const Forms = () => {
  const [alert,setAlert]=useState();
  const [page,setPage] = useState(0);
  const [formData,setFormData]= useState({
    email :"",
    FirstName:"",
    LastName:"",
    CountryNumber:"",
    Number:"",
    JobTitle:"",
    People:"",
    Company:"",
    TaxID:""
  })
  
  const [email,setEmail] = useState("");
  const [firstName,setFirstName] = useState("");
  const [lastName,setLastName] = useState("");
  const [countryNumber,setCountryNumber] = useState("");
  const [number,setNumber] = useState("");
  const [jobTitle,setJobTitle] = useState("");
  const [people,setPeople] = useState("");
  const [company,setCompany] = useState("");
  const [taxID,setTaxID] = useState("");

  useEffect(() => {
   console.log(formData);
  }, [formData]);

  useEffect(() => {
   setAll();
  }, [email, firstName, lastName, countryNumber, number, jobTitle, people, company, taxID]);
     
   const setAll = () => {
    setFormData({
      email :email,
      FirstName:firstName,
      LastName:lastName,
      CountryNumber:countryNumber,
      Number:number,
      JobTitle:jobTitle,
      People:people,
      Company:company,
      TaxID:taxID
    })
   } 


const Signup2 = ({data}) => {
  return <div>Email: {data.email}</div>;
}
   
const Signup3 = ({data}) => {
  return "Signup3 Page Content";
}
  

  const PageDisplay = () =>{
    if(page===0){
      return <form>
        <input onChange={(e) => setEmail(e.target.value)} value={email} type="text" />
        <input onChange={(e) => setFirstName(e.target.value)} value={firstName} type="text" />
        <input onChange={(e) => setLastName(e.target.value)} value={lastName} type="text" />
        <input onChange={(e) => setCountryNumber(e.target.value)} value={countryNumber} type="text" />
        <input onChange={(e) => setNumber(e.target.value)} value={number} type="text" />
        <input onChange={(e) => setJobTitle(e.target.value)} value={jobTitle} type="text" />
        <input onChange={(e) => setPeople(e.target.value)} value={people} type="text" />
        <input onChange={(e) => setCompany(e.target.value)} value={company} type="text" />
        <input onChange={(e) => setTaxID(e.target.value)} value={taxID} type="text" />
      </form>;
    }
    if(page===1){
      return <Signup2 data={formData} />;
    }
    if(page===2){
      return <Signup3 data={formData} />
  }
    if(page===3){
      return( <div>sucess</div>)
    }
}

  return (
    <div>
    <button onClick={() => setAll()}>Trigger SetAll</button>
      <div>Current Page {page   1}</div>
      <button onClick={() => setPage(0)}>Page 1</button>
      <button onClick={() => setPage(1)}>Page 2</button>
      <button onClick={() => setPage(2)}>Page 3</button>
      <div>{PageDisplay()}</div>
    </div>
  );
};
ReactDOM.render(
  <Forms />,
  document.getElementById("root")
);
input[type="text"]{
  display:block;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

  • Related