|
import React, { useReducer } from "react"; |
|
import axios from "axios"; |
|
import ClientContext from "./clientContext"; |
|
import clientReducer from "./clientReducer"; |
|
import { |
|
ADD_CLIENT, |
|
UPDATE_CLIENT, |
|
DELETE_CLIENT, |
|
SET_CURRENT, |
|
CLEAR_CURRENT, |
|
FILTER_CLIENTS, |
|
CLEAR_FILTER, |
|
CLIENT_ERROR, |
|
GET_CLIENTS, |
|
CLEAR_CLIENTS |
|
} from "../types"; |
|
|
|
const ClientState = props => { |
|
const initialState = { |
|
clients: null, |
|
current: null, |
|
filtered: null, |
|
error: null |
|
}; |
|
|
|
const [state, dispatch] = useReducer(clientReducer, initialState); |
|
|
|
// Get Clients |
|
const getClients = async () => { |
|
try { |
|
const res = await axios.get("/api/clients"); |
|
|
|
dispatch({ type: GET_CLIENTS, payload: res.data }); |
|
} catch (error) { |
|
dispatch({ type: CLIENT_ERROR, paylod: error.response.msg }); |
|
} |
|
}; |
|
|
|
// Add Client |
|
const addClient = async client => { |
|
const config = { |
|
headers: { |
|
"Content-Type": "application/json" |
|
} |
|
}; |
|
|
|
try { |
|
const res = await axios.post("/api/clients", client, config); |
|
|
|
dispatch({ type: ADD_CLIENT, payload: res.data }); |
|
} catch (error) { |
|
dispatch({ type: CLIENT_ERROR, paylod: error.response.msg }); |
|
} |
|
}; |
|
|
|
// Update Client |
|
const updateClient = async client => { |
|
const config = { |
|
headers: { |
|
"Content-Type": "application/json" |
|
} |
|
}; |
|
|
|
try { |
|
const res = await axios.put(`/api/clients/${client._id}`, client, config); |
|
|
|
dispatch({ type: UPDATE_CLIENT, payload: res.data.client }); |
|
} catch (error) { |
|
dispatch({ type: CLIENT_ERROR, paylod: error.response.msg }); |
|
} |
|
}; |
|
|
|
// Delete Client |
|
const deleteClient = async id => { |
|
try { |
|
await axios.delete(`/api/clients/${id}`); |
|
|
|
dispatch({ type: DELETE_CLIENT, payload: id }); |
|
} catch (error) { |
|
dispatch({ type: CLIENT_ERROR, paylod: error.response.msg }); |
|
} |
|
}; |
|
|
|
// Clear Clients |
|
const clearClients = () => { |
|
dispatch({ type: CLEAR_CLIENTS }); |
|
}; |
|
|
|
// Set Current Client |
|
const setCurrent = client => { |
|
dispatch({ type: SET_CURRENT, payload: client }); |
|
}; |
|
|
|
// Clear Current Client |
|
const clearCurrent = client => { |
|
dispatch({ type: CLEAR_CURRENT }); |
|
}; |
|
|
|
// Filter Clients |
|
const filterClients = text => { |
|
dispatch({ type: FILTER_CLIENTS, payload: text }); |
|
}; |
|
|
|
// Clear Filter |
|
const clearFilter = () => { |
|
dispatch({ type: CLEAR_FILTER }); |
|
}; |
|
return ( |
|
<ClientContext.Provider |
|
value={{ |
|
clients: state.clients, |
|
current: state.current, |
|
filtered: state.filtered, |
|
error: state.error, |
|
addClient, |
|
deleteClient, |
|
updateClient, |
|
setCurrent, |
|
clearCurrent, |
|
filterClients, |
|
clearFilter, |
|
getClients, |
|
clearClients |
|
}} |
|
> |
|
{props.children} |
|
</ClientContext.Provider> |
|
); |
|
}; |
|
|
|
export default ClientState; |