route
server.get('/todos', opts, async (request, reply) => {
try {
const todos: Array<ITodo> = await todoRepo.getTodos()
return reply.status(200).send({ todos })
} catch (error) {
console.error(`GET /todos Error: ${error}`)
return reply.status(500).send(`[Server Error]: ${error}`)
}
})
api response example
{
"todos": [
{
"_id": "6122803149be955d4f98b1dd",
"name": "111",
"description": "222",
"status": true,
"createdAt": "2021-08-22T16:49:53.545Z",
"updatedAt": "2021-08-22T17:19:06.808Z",
"__v": 0
}
]
}
type defined
type TodoResponse = {
todos: Array<ITodo>
}
API implement method
import axios, { AxiosResponse } from 'axios'
const API_URL = 'http://localhost:8888/api'
const getTodos = async (): Promise<AxiosResponse<TodoResponse>> => {
try {
const todos = await axios.get<TodoResponse>(`${API_URL}/todos`)
return todos
} catch (error) {
console.error(`GET /api/todos ERROR: ${error}`)
throw new Error(`${error}`)
}
}
use API method
const [todos, setTodos] = useState<ITodo[]>([])
useEffect(() => {
fetchTodos()
}, [])
const fetchTodos = async () => {
const { data: {todos} } = await getTodos()
setTodos(todos)
}
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up