Skip to content

Instantly share code, notes, and snippets.

@Karnak19
Last active April 12, 2021 13:08
Show Gist options
  • Save Karnak19/ec31ae291c9345efe14c98c38a78fa47 to your computer and use it in GitHub Desktop.
Save Karnak19/ec31ae291c9345efe14c98c38a78fa47 to your computer and use it in GitHub Desktop.
const BASE_URL = 'https://jsonplaceholder.typicode.com';
export default {
TODOS_URL: `${BASE_URL}/todos`,
USERS_URL: `${BASE_URL}/users`,
};
import { useEffect, useState } from 'react';
import axios from 'axios';
import { TODOS_URL } from './api';
export function useGetAll() {
const [todos, setTodos] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const getAll = async () => {
setError(null);
setLoading(true);
try {
const { data } = await axios.get(TODOS_URL);
setTodos(data);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
getAll();
}, []);
return { todos, error, loading };
}
export function useGetOne(id) {
const [todo, setTodo] = useState({});
useEffect(() => {
const getOne = async () => {
const { data } = await axios.get(`${TODOS_URL}/${id}`);
setTodo(data);
};
getOne();
}, []);
return todo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment