I want to call products from my server with axios in my react project. I am using redux.When I have trigged the actions in component with useeffect , my products have not come but, my products have come not using useeffect.
in my component:
async function get(){
await props.getProducts()
console.log(props.products)
}
useEffect(() => {
get()
}, []); when I write 'get or get()' in square brackets , products loop coming to console continuous
}
my actions:
import axios from "axios"
const url="https://my-expressjs-ap.herokuapp.com/products"
export const getProducts=()=> (dispatch: (arg0: { type: any; payload: any }) => any)=>{
axios
.get(
`https://my-expressjs-ap.herokuapp.com/products`
)
.then((response) =>
dispatch({ type: "GET_PRODUCTS_SUCCESS", payload: response.data })
)
.catch((error) => dispatch({ type: "GET_PRODUCTS_ERROR", payload: error }));
// fetch(url).then(res=> res.json())
// .then(response=>dispatch(({type:"GET_PRODUCTS_SUCCESS",payload:response}))
// ).catch(error=>dispatch({type:"GET_PRODUCTS_ERROR", payload:error}))
}
my reducers:
const INITIAL_STATE={
products:[],
message:''
}
export const reducer=(state=INITIAL_STATE,action: any)=>{
switch(action.type){
case'GET_PRODUCTS_SUCCESS': return {...state, products:action.payload};
case 'GET_PRODUCTS_ERROR': return{...state, message:action.payload}
default: return state;
}
}