NOTE: This is a question I found on StackOverflow which I’ve archived here, because the answer is so effing phenomenal.
If you are not into long explanations, see [Paolo Bergantino’s answer][2].
export default function usePromise(api) { | |
const [state, dispatch] = useReducer( | |
(state, action) => { | |
switch (action.type) { | |
case 'LOADING': | |
return { ...state, loading: true } | |
case 'RESOLVED': | |
return { ...state, loading: false, response: action.response, error: null } | |
case 'ERROR': | |
return { ...state, loading: false, response: null, error: action.error } |
console.log('Client-side code running'); | |
const button = document.getElementById('myButton'); | |
button.addEventListener('click', function(e) { | |
console.log('button was clicked'); | |
fetch('/clicked', {method: 'POST'}) | |
.then(function(response) { | |
if(response.ok) { | |
console.log('click was recorded'); |
NOTE: This is a question I found on StackOverflow which I’ve archived here, because the answer is so effing phenomenal.
If you are not into long explanations, see [Paolo Bergantino’s answer][2].