React Native API data fetch and save as global data - javascript

I am new to React Native. I am creating a simple app that has a Drawer Navigation. After login I want to update user Name and Email on the Drawer. I tried to fetch the the data from API using fetch() in the ComponentDidMount() method, but the problem is when I am setting the data in state it has some promise error.
I want to know the better approach to fetch the data from API and store it so that it can be accessible in any component, usually the auth token and email of the user.
Also anyone suggest a better way to maintain the code with API fetching, I am writing the code for fetch in every component so it become cluttered everywhere.
Update Code:
export class CustomDrawer extends React.Component{
state = {
token: '',
id: '',
user: '',
}
componentDidMount = async() =>{
await this.getAll();
}
setMyToken = () => {
AsyncStorage.getItem('authToken').then((value) =>{
let temp = JSON.parse(value)
this.setState({token : temp.token})
}
getAll = async() => {
await this.setMyToken();
return fetch(`API_URL`).then(response=>response.text().then(text=>{
const data = text && JSON.parse(text)
this.setState({user: data.username, id: data.id})
})).catch(function(error){
console.log(error)
});
}
}

Related

Simulate actioncable websocket receive in webdriverIo

Is there a way during webdriverio runtime to simulate an actioncable receive?
I am using a fork of the package action-cable-react called actioncable-js-jwt for Rails actioncable js connections. Both of these packages are no longer maintained, but actioncable-js-jwt was the only actioncable for react package I could find that supported jwt authentication. I am building an app in my company's platform and jwt authentication is required.
The problem I am running into is that I have a react component which dispatches a redux action to call an api. The api returns a 204, and the resulting data is broadcasted out from Rails to be received by the actioncable connection. This triggers a dispatch to update the redux store with new data. The component does actions based on new data compared to the initial value on component load, so I cannot simply just set initial redux state for wdio - I need to mock the actioncable receive happening.
The way the actioncable subscription is created is:
export const createChannelSubscription = (cable, receivedCallback, dispatch, channelName) => {
let subscription;
try {
subscription = cable.subscriptions.create(
{ channel: channelName },
{
connected() {},
disconnected(res) { disconnectedFromWebsocket(res, dispatch); },
received(data) { receivedCallback(data, dispatch); },
},
);
} catch (e) {
throw new Error(e);
}
return subscription;
};
The receivedCallback function is different for each channel, but for example the function might look like:
export const handleUpdateRoundLeaderWebsocket = (data, dispatch) => {
dispatch({ type: UPDATE_ROUNDING_LEADER, round: data });
};
And the redux state is used here (code snippets):
const [currentLeader, setCurrentLeader] = useState(null);
const userId = useSelector((state) => state.userId);
const reduxStateField = useSelector((state) => state.field);
const onChange = useCallback((id) => {
if (id !== currentLeader) {
if (id !== userId && userId === currentLeader) {
setShow(true);
} else {
setCurrentLeader(leaderId);
}
}
}, [currentLeader, userId]);
useEffect(() => {
onChange(id);
}, [reduxStateField.id, onChange]);
Finally, my wdio test currently looks like:
it('has info dialog', () => {
browser.url('<base-url>-rounding-list-view');
$('#my-button').click();
$('div=Continue').click();
// need new state after the continue click
// based on new state, might show an info dialog
});
Alternatively, I could look into manually updating redux state during wdio execution - but I don't know how to do that and can't find anything on google except on how to provide initial redux state.

React - get request using axios not able to setState

I am new to react and currently working on a project.
I usually use Class Components, however, I am trying to learn Functional Components but I encounter an issue with the setState.
My Component:
function GetCustomerDetailsFc(this: any, props: CustomerModel): JSX.Element {
const [state, setState] = useState('');
async function send(){
try {
const response = await axios.get<CustomerModel>(globals.urls.customerDetails)
store.dispatch(oneCustomerAction(response.data));
console.log(response.data)
setState( {customer: response.data});
} catch (err) {
notify.error(err);
}
}
useEffect(() => {
send();
});
return (
<><h1>{this.state.customer.email}</h1></>
);
}
export default GetCustomerDetailsFc;
I am not sure on how to save state so I can read it.
when I log the request I can see the back-end actually returns data which contains:
User details : (id, email, password , etc...)
An Array of Coupons linked to users purchase.
so basically I can see the request responds properly, however, since I am new I am not sure exactly about the syntax and how I could read properly the data.
Customer Model:
class CustomerModel {
public id: number;
public firstName :string;
public lastName :string;
public email: string;
public token: string;
public password: string;
}
export default CustomerModel;
Note:: I use redux for this project and store data accordingly.
Thanks.
If the returned data is intended to be used locally in this component, then what you pass into useState should match the response you are receiving from the server.
So if for instance your server returns a CostomerModel object, you should initiate your useState with an object -
const [ customer, setCustomer ] = useState({})
try{
const response = await axios.get<CustomerModel>(globals.urls.customerDetails)
...
setCustomer(response);
...
}

Unable to fetch data from firebase firestore database with react native using state

I am building a react native app where I need to place all the data of users in a firebase firestore database into a flatlist. I am unsure of how to do this with all updated react native code, as all other stack overflow questions do not answer this question and I can not find any help elsewhere.
My code for fetching the react native data is:
state = {
data: []
};
unsubscribe = null;
componentDidMount() {
const user = this.props.uid || Fire.shared.uid;
const list = [];
this.unsubscribe = Fire.shared.firestore
.collection("users")
.doc(data)
.onSnapshot(doc => {
list.push(data);
});
this.setState({
data: list
)};
}
componentWillUnmount() {
this.unsubscribe();
}
The database structure is that the user has a name and an email. I try to call this by typing: "{this.state.name.email}", which does not work in the Flatlist. I already initialized my app in another file, where Fire.shared = new Fire(); is exported. If any help would be given on how to export such data into the state properly, I would be largely grateful. Thank you in advance!
The call to setState needs to be in the callback, so:
componentDidMount() {
const user = this.props.uid || Fire.shared.uid;
const list = [];
this.unsubscribe = Fire.shared.firestore
.collection("users")
.doc(data)
.onSnapshot(doc => {
list.push(data);
this.setState({
data: list
)};
});
}

Trying call useQuery in function with react-apollo-hooks

I want to call useQuery whenever I need it,
but useQuery can not inside the function.
My trying code is:
export const TestComponent = () => {
...
const { data, loading, error } = useQuery(gql(GET_USER_LIST), {
variables: {
data: {
page: changePage,
pageSize: 10,
},
},
})
...
...
const onSaveInformation = async () => {
try {
await updateInformation({...})
// I want to call useQuery once again.
} catch (e) {
return e
}
}
...
How do I call useQuery multiple times?
Can I call it whenever I want?
I have looked for several sites, but I could not find a solutions.
From apollo docs
When React mounts and renders a component that calls the useQuery hook, Apollo Client automatically executes the specified query. But what if you want to execute a query in response to a different event, such as a user clicking a button?
The useLazyQuery hook is perfect for executing queries in response to
events other than component rendering
I suggest useLazyQuery. In simple terms, useQuery will run when your component get's rendered, you can use skip option to skip the initial run. And there are some ways to refetch/fetch more data whenever you want. Or you can stick with useLazyQuery
E.g If you want to fetch data when only user clicks on a button or scrolls to the bottom, then you can use useLazyQuery hook.
useQuery is a declarative React Hook. It is not meant to be called in the sense of a classic function to receive data. First, make sure to understand React Hooks or simply not use them for now (90% of questions on Stackoverflow happen because people try to learn too many things at once). The Apollo documentation is very good for the official react-apollo package, which uses render props. This works just as well and once you have understood Apollo Client and Hooks you can go for a little refactor. So the answers to your questions:
How do I call useQuery multiple times?
You don't call it multiple times. The component will automatically rerender when the query result is available or gets updated.
Can I call it whenever I want?
No, hooks can only be called on the top level. Instead, the data is available in your function from the upper scope (closure).
Your updateInformation should probably be a mutation that updates the application's cache, which again triggers a rerender of the React component because it is "subscribed" to the query. In most cases, the update happens fully automatically because Apollo will identify entities by a combination of __typename and id. Here's some pseudocode that illustrates how mutations work together with mutations:
const GET_USER_LIST = gql`
query GetUserList {
users {
id
name
}
}
`;
const UPDATE_USER = gql`
mutation UpdateUser($id: ID!, $name: String!) {
updateUser(id: $id, update: { name: $name }) {
success
user {
id
name
}
}
}
`;
const UserListComponen = (props) => {
const { data, loading, error } = useQuery(GET_USER_LIST);
const [updateUser] = useMutation(UPDATE_USER);
const onSaveInformation = (id, name) => updateUser({ variables: { id, name });
return (
// ... use data.users and onSaveInformation in your JSX
);
}
Now if the name of a user changes via the mutation Apollo will automatically update the cache und trigger a rerender of the component. Then the component will automatically display the new data. Welcome to the power of GraphQL!
There's answering mentioning how useQuery should be used, and also suggestions to use useLazyQuery. I think the key takeaway is understanding the use cases for useQuery vs useLazyQuery, which you can read in the documentation. I'll try to explain it below from my perspective.
useQuery is "declarative" much like the rest of React, especially component rendering. This means you should expect useQuery to be called every render when state or props change. So in English, it's like, "Hey React, when things change, this is what I want you to query".
for useLazyQuery, this line in the documentation is key: "The useLazyQuery hook is perfect for executing queries in response to events other than component rendering". In more general programming speak, it's "imperative". This gives you the power to call the query however you want, whether it's in response to state/prop changes (i.e. with useEffect) or event handlers like button clicks. In English, it's like, "Hey React, this is how I want to query for the data".
You can use fetchMore() returned from useQuery, which is primarily meant for pagination.
const { loading, client, fetchMore } = useQuery(GET_USER_LIST);
const submit = async () => {
// Perform save operation
const userResp = await fetchMore({
variables: {
// Pass any args here
},
updateQuery(){
}
});
console.log(userResp.data)
};
Read more here: fetchMore
You could also use useLazyQuery, however it'll give you a function that returns void and the data is returned outside your function.
const [getUser, { loading, client, data }] = useLazyQuery(GET_USER_LIST);
const submit = async () => {
const userResp = await getUser({
variables: {
// Pass your args here
},
updateQuery() {},
});
console.log({ userResp }); // undefined
};
Read more here: useLazyQuery
You can create a reusable fetch function as shown below:
// Create query
const query = `
query GetUserList ($data: UserDataType){
getUserList(data: $data){
uid,
first_name
}
}
`;
// Component
export const TestComponent (props) {
const onSaveInformation = async () => {
// I want to call useQuery once again.
const getUsers = await fetchUserList();
}
// This is the reusable fetch function.
const fetchUserList = async () => {
// Update the URL to your Graphql Endpoint.
return await fetch('http://localhost:8080/api/graphql?', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: {
data: {
page: changePage,
pageSize: 10,
},
},
})
}).then(
response => { return response.json(); }
).catch(
error => console.log(error) // Handle the error response object
);
}
return (
<h1>Test Component</h1>
);
}
Here's an alternative that worked for me:
const { refetch } = useQuery(GET_USER_LIST, {
variables: {
data: {
page: changePage,
pageSize: 10,
},
},
}
);
const onSaveInformation = async () => {
try {
await updateInformation({...});
const res = await refetch({ variables: { ... }});
console.log(res);
} catch (e) {
return e;
}
}
And here's a similar answer for a similar question.
Please use
const { loading, data, refetch } = useQuery(Query_Data)
and call it when you need it i.e
refetch()

How to structure API code in a Vue Single-Page App?

I'm building a fairly large SPA using Vue (and Laravel for RESTful API). I'm having a hard time finding resources about this online - what's a good practice to organise the code that communicates with the server?
Currently I have src/api.js file, which uses axios and defines some base methods as well as specific API endpoints (truncated):
import axios from 'axios';
axios.defaults.baseURL = process.env.API_URL;
const get = async (url, params = {}) => (await axios.get(url, { params }));
const post = async (url, data = {}) => (await axios.post(url, data));
export const login = (data) => post('users/login', data);
And then in my component, I can do
...
<script>
import { login } from '#/api';
...
methods: {
login() {
login({username: this.username, password: this.password})
.then() // set state
.catch() // show errors
}
}
</script>
Is this a good practice? Should I split up my endpoints into multiple files (e.g. auth, users, documents etc.)? Is there a better design for this sort of thing, especially when it comes to repetition (e.g. error handling, showing loading bars etc.)?
Thanks!
If you're just using Vue and expect to be fetching the same data from the same component every time, it's generally idiomatic to retrieve the data and assign it using the component's mounted lifecycle hook, like so:
<template>
<h1 v-if="name">Hello, {{name}}!</h1>
</template>
<script>
export default {
data() {
return {
name: '',
}
},
mounted() {
axios.get('https://example.com/api')
.then(res => {
this.name = res.data.name;
})
.catch(err =>
// handle error
);
},
};
</script>
If you're going to be using Vuex as mentioned in one of your comments, you'll want to put your API call into the store's actions property.
You'll end up with a Vuex store that looks something like this:
const store = new Vuex.Store({
state: {
exampleData: {},
},
mutations: {
setExampleData(state, data) {
state.exampleData = data;
},
},
actions: {
async getExampleData() {
commit(
'setExampleData',
await axios.get('https://www.example.com/api')
.then(res => res.data)
.catch(err => {
// handle error
});
);
},
}
});
Of course, breaking out your state, actions, and mutations into modules as your app grows is good practice, too!
If you use Vue CLI it will setup a basic project structure. With a HelloWorld component. You will want to break your vue app into components. Each component should have a defined role that ideally you could then unit test.
For example lets say you want to show list of products then you should create a product list component.
<Products :list="products" />
In your app you would do something like
data() {
return {
prodcuts: []
}
},
mounted() {
axios.get('/api/products').then(res => {
this.products = res.data
})
}
Whenever you see something that "is a block of something" make a component out of it, create props and methods and then on the mounted hook consume the api and populate the component.

Categories

Resources