jeudi 28 novembre 2019

React Update Fetch on Checkbox Click

I have a component(Card) that has checkboxes that are tracked in a localhost database using Postgres. When I check or uncheck the box, an entry gets put into the networkusers table. The problem is that when I check or uncheck the box, and then click on a button to render a different component and then come back to the Card component with the checkboxes, the boxes are not showing the updated check. However, if I sign out and sign back in, all the boxes are updated and in sync with database. So how do I get the component to render (or fetch again?) as soon as checkbox is changed in the following component? TY.

import React, { useState } from "react";

const onUpdateCB = (ischecked, loginuser, userid, setisChecked,handleCheck,event) => {

  console.log(ischecked, loginuser, userid);

  fetch('http://localhost:3000/cb', {
      method: 'post',
      headers: {'Content-Type':'application/json'},
      body:JSON.stringify({
      loginuser,
      userid,
      ischecked: ischecked
    })
  }).then(setisChecked(ischecked)); 
};

const Card = props => {
  const [isChecked, setisChecked] = useState(props.ischecked);
  return (
    <div
      className="pointer bg-light-green dib br3 pa3 ma2 shadow-5"
      onClick={() => props.handleClick(props.id)}
      //onClick={(e) => e.stopPropagation()}

    >
      <div>
        <h3>{props.name}</h3>
        <p>{props.company}</p>
        <p>{props.phone}</p>
        <p>{props.email}</p>
        <p>{props.city}</p>
      </div>
      <div>
        My Network
        <input
          className="largeCheckbox"
          type="checkbox"
          checked={isChecked}
          onClick={(event) =>
            onUpdateCB(!isChecked, props.loginuser.id, props.id, setisChecked,event.stopPropagation())
          }
        />
      </div>
    </div>
  );
};

export default Card;



Aucun commentaire:

Enregistrer un commentaire