Home > Blockchain >  Wait for map response before return (React JS)
Wait for map response before return (React JS)

Time:12-21

here is the code :

const [isAcces, setIsAcces] = useState(false); 

useEffect(() => {
    accesList
        .filter((acces) => acces.idAcces === 2)
        .map((acces, index) => setIsAcces(true));
}, []);

return <div>Hello World</div>;

I want to render 'Hello World' if 'isAcces' is equal true. If not, I use <Navigate to="/" /> to redirect.

I know 'useEffect' is render AFTER the return, but I can't find a solution to solve my issue (and of course, 'isAcces' is always false before the redirection).

I found on Google that I can use the 'Promises', but I don't know how it's work.

Can somebody help me ?

Thank you !

CodePudding user response:

If I understand correctly you are looping an array and if there are items there that equal 2, you set your isAcces true, correct?

If yes you don't need a map() after the filter

You can simplify your code a bit.

function YourComponent({ accesList }) {
  const [isAcces, setIsAcces] = useState(false); 
   
  useEffect(() => {
    const newArr = accesList.filter((acces) => acces.idAcces === 2);
       
    if (newArr.length > 0) {
      setIsAcces(true); 
    }

  }, []);

  useEffect(() => {
    if (isAcces) {
      // import history from react-router-dom or any method to navigate to another route
      history.push("/");
    }
  }, [isAcces]);

  return <div>hello world!</div>
}

CodePudding user response:

It looks like you should be using useMemo for isAccess. That will evaluate before the return, and it depends on accesList. And since you're just looking for a boolean based on whether a matching item is in the list, use some:

const isAcces = useMemo(
    () => accesList.some((acces) => acces.idAcces === 2),
    [accesList]
);

if (!isAccess) {
    return <Navigate to="/" />; // ??
} 

return <div>Hello World</div>;

CodePudding user response:

export default function App() {
  const accesList = [{ idAcces: 1 }, { idAcces: 2 }];
  const [isAcces, setIsAcces] = useState(false);

  useEffect(() => {
    let showHelloWorld = accesList.some((acces) => acces.idAcces === 2);
    if (showHelloWorld) {
      setIsAcces(true);
    } else {
      //history.push("/");
    }
  }, []);

  return isAcces && <div>Hello World</div>;
}
  • Related