302 Found on Laravel in GET request made by cross-fetch on react - laravel

I have a component with a table, when this component mounts I would like to make a request to get data that fills the table.
In my table component:
componentDidMount() {
const { fetchTransactions } = this.props;
fetchTransactions()
}
This came from (I'm using redux):
const mapDispatchToProps = dispatch => ({
fetchTransactions: value => dispatch(fetchTransactions())
})
And the action:
export function fetchTransactions() {
return function (dispatch) {
dispatch(requestTransactions())
return fetch('/getTransactions')
.then(
response => response.json(),
error => console.log('An error occurred.', error)
)
.then(json => dispatch(receiveTransactions(json)))
}
}
When the component mounts, the action is dispatched and the fetch too, but the response is a 302 found as you can see here:
Using the browser it work as I expect:
Any ideas? thank you.

Related

Dispatch actions from a custom hook using useQuery

I'm trying to write a custom hook that uses useQuery from react-query. The custom hook takes in the id of an employee and fetches some data and returns it to the consuming component. I want to be able to dispatch a redux action to show a loading indicator or show an error message if it fails. Here is my custom hook.
export default function useEmployee(id) {
const initial = {
name: '',
address: '',
}
const query = useQuery(['fetchEmployee', id], () => getEmployee(id), {
initialData: initial,
onSettled: () => dispatch(clearWaiting()),
onError: (err) => dispatch(showError(err)),
})
if (query.isFetching || query.isLoading) {
dispatch(setWaiting())
}
return query.data
}
When I refresh the page, I get this error in the browser's console and I'm not sure how to fix this error?
Warning: Cannot update a component (`WaitIndicator`) while rendering a different component (`About`).
To locate the bad setState() call inside `About`, follow the stack trace as described in
The issue is likely with dispatching the setWaiting action outside any component lifecycle, i.e. useEffect. Move the dispatch logic into a useEffect hook with appropriate dependency.
Example:
export default function useEmployee(id) {
const initial = {
name: '',
address: '',
};
const { data, isFetching, isLoading } = useQuery(['fetchEmployee', id], () => getEmployee(id), {
initialData: initial,
onSettled: () => dispatch(clearWaiting()),
onError: (err) => dispatch(showError(err)),
});
useEffect(() => {
if (isFetching || isLoading) {
dispatch(setWaiting());
}
}, [isFetching, isLoading]);
return data;
}

How to render errors with apollo-link-error

I would like to use apollo client error link to create a MUI snackbar displaying any error that is returned by graphql.
The setup is a Nextjs web app using Material-ui and Apollo Client.
From Apollo documentation on Error links an error link can be created which will handle errors returned by the graphql API. The Apollo error link can not render anything it self as it will return void.
import { onError } from "#apollo/client/link/error";
// Log any GraphQL errors or network error that occurred
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
My initial thought was to use hooks and context. Creating a hook which the Apollo error link can push notifications on and a context provider in my _app.ts.
However the Apollo client is not a functional component hence this will not work.
I did think about creating a function to handle onError callback in Apollo queries and mutations but it seems like a lot of work to put an onError function on each query/mutation.
This can be handled using context. You have to do some changes to your component hierarchy.
ContextProvider => ApolloProvider
Make sure both are used in different components. Otherwise, you will not able to access hooks.
Ex: You should be able to access the hook inside the Root component, where you can add ApolloProvider.
I've created an example hope that helps (not using apollo but you can add): https://stackblitz.com/edit/react-ts-m7swyo
import React, { createContext, useContext, useReducer } from "react";
import { render } from "react-dom";
import "./style.css";
const Context = createContext({});
const Root = () => {
const { state, dispatch } = useContext(Context);
return (
<ApolloProvider
client={
new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
// Do something and dispatch to context
// dispatch({ type: 'ERROR', error: graphQLErrors || networkError });
}),
]),
})
}
>
<App />
</ApolloProvider>
);
};
const reducer = (state, action) => {
if (action.type === "ERROR") {
return { ...state, ...action.payload };
}
return state;
};
const App = () => {
const [state, dispatch] = useReducer(reducer, {});
return (
<Context.Provider
value={{
state,
dispatch,
}}
>
<Root />
</Context.Provider>
);
};
render(<App />, document.getElementById("root"));

error Policy in Apollo Client React does'nt work

I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please!
Here my code:
query { animal {
name
age }, school {
name
numberfd } } `
const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, {
errorPolicy:'all',
onCompleted: (res) => {console.log("complete",res)},
onError : (res,data) => {console.log("ERRRR",res,data)},
})
and i want to receive:
{
error:[...], data:[animal:[...]] }
but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/
onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback.
After useQuery you can add:
console.log('data', data)
console.log('error', error)
I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.
I created an ErrorLink like this:
private createErrorLink = () => {
return new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
// filter out errors you don't want to display
const errors = filterSomeErrors(response.errors);
if (errors && response?.data) {
response.data.errors = errors;
}
return response;
});
});
};
Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.
Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!

Get vuex store state after dispatching an action

I'm creating a chat application in Laravel 6 + Vue + Vuex. I want make a call to vuex store and get a state after a dispatch actions is complete and then I want to do some processing on that state in my vue component.
In ChatWindow component
mounted: function () {
this.$store.dispatch('setContacts').then(() => {
console.log('dispatch called')
// I want to call the getter here and set one of the data property
});
}
action.js
setContacts: (context) => {
axios.post('/users').then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
});
}
mutators.js
setContacts: (state, users) => {
state.contacts = users;
},
Please see the screenshot below. The then method of dispatch is running before setContacts in action.js.
I need to call the getter after completing dispatch action. (which will effectively set the contacts state). Then, I want to get the contacts through getContacts getter like this.
getters.js
getContacts: (state) => {
return state.contacts;
}
I also tried calling computed property in then in mounted and it didn't work. Also, shouldn't 'dispatch called' in mounted run after console.log of setContacts in action.js as it is in then method? Thanks!
Maybe you could wrap axios call inside another promise.
return new Promise((resolve, reject) => {
axios.post('/users')
.then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
resolve('Success')
})
.catch(error => {
reject(error)
})
})
And then
this.$store.dispatch('setContacts')
.then(() => {
console.log('dispatch called')
console.log('getter ', this.$store.getters.contacts)
});
Let me know what happens. It was working for a small demo that I tried.

Can the completion of one async call be sequenced before the start of another using useEffect?

I'm trying to use useEffect in my React app but also refactor things more modularly. Shown below is the heart of actual working code. It resides in a Context Provider file and does the following:
1. Calls AWS Amplify to get the latest Auth Access Token.
2. Uses this token, in the form of an Authorization header, when an Axios GET call is made to an API Endpoint.
This works fine but I thought it would make more sense to move Step #1 into its own useEffect construct above. Furthermore, in doing so, I could then also store the header object as its own Context property, which the GET call could then reference.
Unfortunately, I can now see from console log statements that when the GET call starts, the Auth Access Token has not yet been retrieved. So the refactoring attempt fails.
useEffect(() => {
const fetchData = async () => {
const config = {
headers: { "Authorization":
await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert('Error getting authorization token: '.concat(error))
})
}};
await axios.get('http://127.0.0.1:5000/some_path', config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert('Error getting data from endpoint: '.concat(error));
});
};
fetchData();
}, [myContextObject.some_data]);
Is there a way of refactoring my code into two useEffect instances such that the first one will complete before the second one starts?
You could hold the config object in a state. This way you can separate both fetch calls and trigger the second one once the first one finished:
const MyComponent = props => {
const myContextObject = useContext(myContext);
const [config, setConfig] = useState(null);
useEffect(() => {
const fetchData = async () => {
const config = {
headers: {
Authorization: await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert("Error getting authorization token: ".concat(error));
})
}
};
setConfig(config);
};
fetchData();
}, [myContextObject.some_data]);
useEffect(() => {
if (!config) {
return;
}
const fetchData = async () => {
await axios
.get("http://127.0.0.1:5000/some_path", config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert("Error getting data from endpoint: ".concat(error));
});
};
fetchData();
// This should work for the first call (not tested) as it goes from null to object.
// If you need subsequent changes then youll have to track some property
// of the object or similar
}, [config]);
return null;
};

Resources