Use Reducer

Post demo

useState

const Post = (): JSX.Element => {
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<boolean>(false);
const [post, setPost] = useState<{ [key: string]: any }>({});
const handleFetch = (): void => {
  setLoading(true);
  setError(false);
  fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then((res) => res.json())
    .then((data) => {
      setLoading(false);
      setPost(data);
    })
    .catch((err) => {
      setLoading(false);
      setError(true);
    });
};

 return (
    <div>
      <button onClick={handleFetch}>
        {loading ? "Wait..." : "Fetch the post"}
      </button>
      <p>{post?.title}</p>
      <span>{error && "Something went wrong!"}</span>
    </div>
  );
}

useReducer

Form demo

useState

useReducer

Last updated