user18541276
user18541276

Reputation:

How to update state in react?

I am new to react....I am stuck in this problem for many days..but not able to find a solution.. I want to achieve this:

When the Patent component mounts I want to fetch data from my server which am I doing by useeffect and display it on the screen (the data is list of emails)....Then there is add email button..when user click on it a popup Modal () appears which I handled through EmailModal usestate...In the popup user can add new email and onclick submit button the email get send to the server ...and the popup closes and screen should get updated with this new email along with previous email

There are two problem which I am not able to solve 1 when I click on submit , the screen does not rerenders and show the updated list 2 When I am typing in Modal(popup) to add email it is blinking ( I think it is rerendering on each letter type..

I am not able to solve this...Any help would be appreciated..Thank you in advanced ( if possible please show the correct way of implementing this)

const Patent = () => {

  const xx = [];
  
  const [EmailModal, setEmailModal] = useState(false);

  const changeState1 = () => {  
     
      xx.push(
      <Card
      title= {typemail}
     asset={<img width="24" height="24" src="/assets/settings/email.svg" alt="" />} />
     )
   
   
    const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "jijfijwijfijfisjifffsNDc0MjY0NzAsImsdsddI3MCwicmxsdddadfAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"fasasgOtg1","sender_email":typemail})
    };
     
          fetch('https://demo.car.com/aura/em/li', requestOptions)
          .then(response => response.json())
          .then(data =>  console.log(data));    
  
  

      setvr(xx);
     setEmailModal(false)

 }; 


  const Frapper = ({ tit, subtit, child }) => (
    <div className={styles.frapper}>
      <div className={styles.contain}>
      <h4 className={styles.tit}>{tit}</h4>
      <Button
        className={styles.btn12}
        onClick={() => setEmailModal(true)}      
      > {'+ Add Email'} </Button> 
      </div>    
      <h7 className={styles.subtitle}>{subtitle}</h7>
      {children}
    </div>
  )
    
   const [typemail, settypemail] = useState("");
   const [fruits, setFruits] = useState([]);
   const [vr,setvr] = useState([]);

   useEffect(() => {
   
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "asdaijdcisjciASDASDADAcCI6MTY0ODAzMTI3MCwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
        body: JSON.stringify({"firebase_id":"MgOtg1"})
    };
   
        fetch('https://demo.car.com/aura/em/li', requestOptions)
        .then(response => response.json()) 
        .then(data => setFruits(data.success));    
   
   }, []);

  

   for(let i = 0;i<fruits.length;i++){
     xx.push(
      <Card title= {fruits[i].SenderEmail}  status={fruits[i].Status} asset={<img width="24" height="24" src="/assets/settings/email.svg" alt="" />} />,

      );
   }
    
  useEffect(() => {
     
  }, [xx]);

      return (
        <>
          <Frapper tit="Emails"  subtitle="Authenticate emails">
            <div className={styles.integrationContainer}>
              <div className={styles.frapper}>
              {xx.map(data => (
                <div>{data}</div>
              ))}
              
           <Modal
          visible={showEmailModal}
         
          footer={null}
          onCancel={() => setEmailModal(false)}
          style={{ overflow: "hidden", borderRadius: "15px", padding: "0px", height: "300px" }}
        >
          <h7 className={styles.modalTitle}>New Email</h7>
          <CustomInput 
        placeholder="Enter your Email Address"
        onChange={settypemail}
        value={typemail}
        style={{ maxWidth: "700px", margin: "30px 0px 20px 0px" }} />

        <Button
        className={styles.btn}
        onClick={changeState1}   
      > {'Submit'} </Button>                
          <div className={`${styles.row} ${styles.alignEnd}`}>       
          </div>
        </Modal>                       
         </div>
         </div>
          </Frapper>
         
      </>
      );
  
}

Upvotes: 1

Views: 174

Answers (1)

Bao Huynh
Bao Huynh

Reputation: 1054

I am not sure if this will fix your issue, but since you are not allowed to mutate the state directly (this is a React-specific thing), you cannot .push onto the state array directly. When dealing with states that are arrays, you should use the destructuring syntax to add new element.

More info can be read here: https://javascript.plainenglish.io/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

Can you try this

const changeState1 = () => {  
    const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "jijfijwijfijfisjifffsNDc0MjY0NzAsImsdsddI3MCwicmxsdddadfAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"fasasgOtg1","sender_email":typemail})
    };
     
    fetch('https://demo.car.com/aura/em/li', requestOptions)
        .then(response => response.json())
        .then(data =>  console.log(data));    
  
  
     const newElement = (
       <Card
         title= {typemail}
         asset={<img
                  width="24"
                  height="24"
                  src="/assets/settings/email.svg" alt=""
                 />}
       />
     )
     // Update state using array destructuring syntax
     setvr(curr => [...curr, newElement]);
     setEmailModal(false)

 };

Upvotes: 1

Related Questions