0
import React from "react";
import { UserContext } from "./../contexts";
import {
  removeStoredAuthData,
  storedAuthIsValid,
  storeNewAuthData,
} from "./../utils/auth";
import { getUserInfos } from "./../api/userAuthentication";

class UserProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: "",
    };
  }

  render() {
    return (
      <UserContext.Provider
        value={{
          user: this.state.user,
          clearUserProfile: () => {
            const user = "";
            removeStoredAuthData();
            this.setState({ user });
          },
          saveUserProfile: (response) => {
            const user = response.data;
            storeNewAuthData(response);
            this.setState({ user });
          },
          populateUserProfile: (displayLoader, hideLoader) => {
            const storedToken = localStorage.getItem("appsante-token");
            const storedId = localStorage.getItem("appsante-id");
            if (storedAuthIsValid()) {
              displayLoader(() => {
                getUserInfos(storedId)
                  .then((response) => {
                    const user = { ...response.data, token: storedToken };
                    this.setState({ user }, hideLoader());
                  })
                  .catch((error) => console.log(error));
              });
            }
          },
        }}
      >
        {this.props.children}
      </UserContext.Provider>
    );
  }
}

export default UserProvider;

Hi everyone !

I trying to convert a React class component into a function component, with hooks.

But I can't find a way to deal properly with that line :

this.setState({ user }, hideLoader());

Unlike setState in class components, useState doesn't take a callback as second parameter, and I can't find how to achieve it with useEffect.

Could anyone help me ? Thanks !

1
  • 1
    this.setState({ user }, hideLoader()); That shouldn't work unless it's a HOF. Do you mean this.setState({ user }, hideLoader);? Sep 16, 2020 at 19:27

2 Answers 2

0

Because the loader's presence can't be determined from the value in / change in user alone, you'll need another state variable, maybe one that contains the callback - perhaps call it hideLoader. After getUserInfos resolves, call setHideLoader with the callback, so that a useEffect hook with that function as a dependency can see the change and call the callback:

const [hideLoader, setHideLoader] = useState();
useEffect(() => {
  if (hideLoader) {
    hideLoader(); // or, if this is a HOF: hideLoader()()
    setHideLoader(); // callback done; remove callback from state
  }
}, [hideLoader]);
// ...
  populateUserProfile: (displayLoader, hideLoaderParam) => {
    // ...
    getUserInfos(storedId)
      .then((response) => {
        setUser({ ...response.data, token: storedToken }); // hook version
        setHideLoader(hideLoaderParam);
      })

and the rest of your code can be mostly the same - only call setHideLoader up above, inside getUserInfos.

0

I think you should do this :-

import React, { useState } from 'react';
    
const [user, setUser] = useState("");
    
populateUserProfile: async (displayLoader, hideLoader) => {
                const storedToken = localStorage.getItem("appsante-token");
                const storedId = localStorage.getItem("appsante-id");
                if (storedAuthIsValid()) {
                  displayLoader();
                    let  response = await getUserInfos(storedId)
                    const user = { ...response.data, token: storedToken };
                    setUser(user);
                    hideLoader();
                  };
                }
   

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.