简体   繁体   中英

How use Local Storage in Functional Component React

How can I use LocalStorage in a functional component like this

I know how do this in a class component but can I solve this problem in this case?

ERROR: 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));
    }
  });

In your first useEffect , the repositories is your state which an array. Not a function.

Also, in your second useEffect you need to make correction to the way you access the prevState in hooks.

Fix for 1st useEffect

export default function Main() {
  const [newRepo, setNewRepo] = useState('');
  const [repositories, setRepositories] = useState([]);
  const [clearInput] = useState([]);
  const [loading, setLoading] = useState(false);

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

    if (localRepoItems) {
        setRepositories(JSON.parse(localRepoItems));
    }

  }, []); // do not give the dependency as repositories as it will go to infinite loop

  });

To obtain previous state in hooks, you can write a little custom hook: Like this:

export const usePrevious = value => {
  const ref = React.useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

Usage in your component:

const prevRepositories = usePrevious(repositories);
useEffect(() => {
    if (prevRepositories.length !== repositories.length) {
        localStorage.setItem('repositories', JSON.stringify(repositories));
    }
  }, [repositories]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM