Skip to content
Advertisement

Sibling component not re-rerendering on state change (using useEffect, useState and Context)

In my Main.js I create a first global state with a username and a list of users I’m following.

Then, both the Wall component and FollowingSidebar render the list of follows and their messages (plus the messages of the main user).

So far so good. But in a nested component inside FollowingSidebar called FollowingUser I have an onClick to remove a user. My understanding is that, because I change the state, useEffect would take care of the Wall component to re-render it, but nothing happens… I’ve checked several examples online but nothing has helped my use case so far.

Needless to say I’m not overly experienced with React and Hooks are a bit complex.

The code here:

Main.js:

import React, { useEffect, useState } from "react";
import ReactDom from "react-dom";
import db from "./firebase.js";

// Components
import Header from "./components/Header";
import FollowingSidebar from "./components/FollowingSidebar";
import SearchUsers from "./components/SearchUsers";
import NewMessageTextarea from "./components/NewMessageTextarea";
import Wall from "./components/Wall";

// Context
import StateContext from "./StateContext";

function Main() {
  const [mainUser] = useState("uid_MainUser");
  const [follows, setFollows] = useState([]);

  const setInitialFollows = async () => {
    let tempFollows = [mainUser];
    const user = await db.collection("users").doc(mainUser).get();
    user.data().following.forEach(follow => {
      tempFollows.push(follow);
    });
    setFollows(tempFollows);
  };

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

  const globalValues = {
    mainUserId: mainUser,
    followingUsers: follows
  };

  return (
    <StateContext.Provider value={globalValues}>
      <Header />
      <FollowingSidebar />
      <SearchUsers />
      <NewMessageTextarea />
      <Wall />
    </StateContext.Provider>
  );
}

ReactDom.render(<Main />, document.getElementById("app"));

if (module.hot) {
  module.hot.accept();
}

FollowingSidebar component:

import React, { useState, useEffect, useContext } from "react";
import db from "../firebase.js";
import StateContext from "../StateContext";
import FollowingUser from "./FollowingUser";

export default function FollowingSidebar() {
  const { followingUsers } = useContext(StateContext);
  const [users, setUsers] = useState(followingUsers);

  useEffect(() => {
    const readyToRender = Object.values(followingUsers).length > 0;
    if (readyToRender) {
      db.collection("users")
        .where("uid", "in", followingUsers)
        .get()
        .then(users => {
          setUsers(users.docs.map(user => user.data()));
        });
    }
  }, [followingUsers]);

  return (
    <section id="following">
      <div className="window">
        <h1 className="window__title">People you follow</h1>
        <div className="window__content">
          {users.map((user, index) => (
            <FollowingUser avatar={user.avatar} username={user.username} uid={user.uid} key={index} />
          ))}
        </div>
      </div>
    </section>
  );
}

FollowingUser component:

import React, { useState, useContext } from "react";
import db from "../firebase.js";
import firebase from "firebase";
import StateContext from "../StateContext";

export default function FollowingUser({ avatar, username, uid }) {
  const { mainUserId, followingUsers } = useContext(StateContext);
  const [follows, setFollows] = useState(followingUsers);

  const removeFollow = e => {
    const userElement = e.parentElement;
    const userToUnfollow = userElement.getAttribute("data-uid");

    db.collection("users")
      .doc(mainUserId)
      .update({
        following: firebase.firestore.FieldValue.arrayRemove(userToUnfollow)
      })
      .then(() => {
        const newFollows = follows.filter(follow => follow !== userToUnfollow);
        setFollows(newFollows);
      });
    userElement.remove();
  };

  return (
    <article data-uid={uid} className="following-user">
      <figure className="following-user__avatar">
        <img src={avatar} alt="Profile picture" />
      </figure>
      <h2 className="following-user__username">{username}</h2>
      <button>View messages</button>
      {uid == mainUserId ? "" : <button onClick={e => removeFollow(e.target)}>Unfollow</button>}
    </article>
  );
}

Wall component:

import React, { useState, useEffect, useContext } from "react";
import db from "../firebase.js";
import Post from "./Post";
import StateContext from "../StateContext";

export default function Wall() {
  const { followingUsers } = useContext(StateContext);
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    console.log(followingUsers);
    const readyToRender = Object.values(followingUsers).length > 0;
    if (readyToRender) {
      db.collection("posts")
        .where("user_id", "in", followingUsers)
        .orderBy("timestamp", "desc")
        .get()
        .then(posts => setPosts(posts.docs.map(post => post.data())));
    }
  }, [followingUsers]);

  return (
    <section id="wall">
      <div className="window">
        <h1 className="window__title">Latest messages</h1>
        <div className="window__content">
          {posts.map((post, index) => (
            <Post avatar={post.user_avatar} username={post.username} uid={post.user_id} body={post.body} timestamp={post.timestamp.toDate().toDateString()} key={index} />
          ))}
        </div>
      </div>
    </section>
  );
}

StateContext.js:

import { createContext } from "react";

const StateContext = createContext();

export default StateContext;

Advertisement

Answer

The main issue is the setting of state variables in the Main.js file (This data should actually be part of the Context to handle state globally).

Below code would not update our state globally.

   const globalValues = {
     mainUserId: mainUser,
     followingUsers: follows
   };

We have to write state in a way that it get’s modified on the Global Context level. So within your Main.js set state like below:

  const [globalValues, setGlobalValues] = useState({
    mainUserId: "uid_MainUser",
    followingUsers: []
  });

Also add all your event handlers in the Context Level in Main.js only to avoid prop-drilling and for better working.

CODESAND BOX DEMO: https://codesandbox.io/s/context-api-and-rendereing-issue-uducc

Code Snippet Demo:

import React, { useEffect, useState } from "react";
import FollowingSidebar from "./FollowingSidebar";

import StateContext from "./StateContext";
const url = "https://jsonplaceholder.typicode.com/users";

function App() {
  const [globalValues, setGlobalValues] = useState({
    mainUserId: "uid_MainUser",
    followingUsers: []
  });

  const getUsers = async (url) => {
    const response = await fetch(url);
    const data = await response.json();

    setGlobalValues({
      ...globalValues,
      followingUsers: data
    });
  };

  // Acts similar to componentDidMount now :) Called only initially
  useEffect(() => {
    getUsers();
  }, []);

  const handleClick = (id) => {
    console.log(id);
    const updatedFollowingUsers = globalValues.followingUsers.filter(
      (user) => user.id !== id
    );
    setGlobalValues({
      ...globalValues,
      followingUsers: updatedFollowingUsers
    });
  };

  return (
    <StateContext.Provider value={{ globalValues, handleClick }}>
      <FollowingSidebar />
    </StateContext.Provider>
  );
}

export default App;
Advertisement