How to use Localstorage in a functional React component

Asked

Viewed 828 times

0

How can I use Localstorage in this case

the way I did works only with class component

Error that appears is: Typeerror: repositories is not a Function

    export default function Main() {

    const [newRepo, setNewRepo] = useState('');
    const [repositories, setRepositories] = useState([]);
    const [clearInput] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        repositories(localStorage.getItem('repositories'));

        if (repositories) {
            setRepositories(JSON.parse(repositories));
        }
    }, [repositories]);

    useEffect((_, prevState) => {
        if (prevState.repositories !== repositories) {
            localStorage.setItem('repositories', JSON.stringify(repositories));
        }
    });
  • What do you mean on the line repositories(localStorage.getItem('repositories'));? It doesn’t make any sense. It would be setRepositories?

1 answer

-1

const App = () => {
  const [repositories, setRepositories] = useState([]);

  useEffect(() => {
    const repositoriesLocal = JSON.parse(localStorage.getItem('repositories'));

    setRepositories(repositoriesLocal)
  }, [])

  return <div>
    {repositories.map(item => <li>{item.name}</li>)}
  </div>;
};
  • Matheus, your question would be of quality if, in addition to the code, you described what error the user made. Thus you allow a greater understanding of the problem on the part of those who ask and make knowledge reusable. Just posting the code encourages nothing but a ctrl + C and ctrl + V I hope to see you around here still helping the community in the best way possible. Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.