Skip to content Skip to sidebar Skip to footer

Reactjs: How To Update Vote Counts In Reactjs

The code below was designed to update a voting system. It works fine by displaying the results as the page loads. Here is my problem: I need to update each user's vote any time the

Solution 1:

You should set your data state after getting the vote data from the fetch response. You have person_id in your handler and getting an array including vote value. So, map through your data state find the relevant person and update its vote value.

classAppextendsReact.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: false
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", name: "Tony", vote: "3" },
        { id: "2", name: "Mark", vote: "6" },
        { id: "3", name: "Joy", vote: "2" }
      ]
    });
  }

  handleVote(person_id, person_vote) {
    const data_vote = {
      person_id: person_id,
      person_vote: person_vote
    };
    axios
      .get("http://localhost/vote.php", { data_vote })
      .then(response => {
        const newData = this.state.data.map(person => {
          if (person.id !== person_id) return person;
          return { ...person, vote: response.data[0].vote };
        });
        this.setState(state => ({
          data: newData
        }));
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <span><label><ul>
            {this.state.data.map(person => (
              <likey={person.id}>
                {person.name} --(vote count: {person.vote})
                <br /><inputtype="button"value="Get Vote Counts"onClick={() => this.handleVote(person.id, person.vote)}
                />
              </li>
            ))}
          </ul></label></span>
    );
  }
}

Try to avoid using an index as a key. You have a person.id so use it in your map method. Also, as an enhancement, you can refactor your code and create a Person component. You can pass the related data and vote handler then setup the update logic there.

classAppextendsReact.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: false,
    };
  }

  componentDidMount() {
    this.setState({
      data: [
        { id: "1", name: "Tony", vote: "3" },
        { id: "2", name: "Mark", vote: "6" },
        { id: "3", name: "Joy", vote: "2" },
      ],
    });
  }

  handleVote = (person) => {
    const data_vote = {
      person_id: person.id,
      person_vote: person.vote,
    };
    axios
      .get("http://localhost/vote.php", { data_vote })
      .then((response) => {
        const newData = this.state.data.map((el) => {
          if (el.id !== person.id) return el;
          return { ...el, vote: response.data[0].vote };
        });
        this.setState({ data: newData });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  render() {
    return (
      <span><label><ul>
            {this.state.data.map(person => (
              <Personkey={person.id}person={person}handleVote={this.handleVote}
              />
            ))}
          </ul></label></span>
    );
  }
}

constPerson = (props) => {
  const { person, handleVote } = props;
  constonVote = () => handleVote(person);
  return (
    <li>
      {person.name} --(vote count: {person.vote})
      <br /><inputtype="button"value="Get Vote Counts"onClick={onVote} /></li>
  );
};

Solution 2:

So, since your handler function is getting the person_id and your call is returning the new vote count, you should update the current person object in your data table in state.

Here is an example:

Updating the vote count for the current user

Post a Comment for "Reactjs: How To Update Vote Counts In Reactjs"