I want to store usere_id in global value state so i create global.js
module.exports = {
users_id: "",
};
and import it in post.js , so how can store data in Global.users_id and use it anywhere i want ...
i tried this
Login = async () => {
const response = await fetch("http://192.168.6.107:8080/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
});
const data = await response.json();
console.log("data", data);
console.log("data.suc", data.success);
if (data.success) {
AsyncStorage.setItem("user", JSON.stringify(data.user));
console.log("DATAAA>>>>",data)
const global= data.user.users_id
const global2= GLOBAL.users_id.setState({
users_id:global
})
console.log("global",global2)
}
return data.success;
};
I want to get users_id from this data
DATAAA>>>> Object {
"success": true,
"user": Array [
Object {
"password": "ddd",
"username": "ddd",
"users_id": 1,
},
],
}
You can declare a global variable anywhere like this:
global.userID = 3
// and use it Login like this
global.userID // value = 3
however it's not recommended doing this very often. Maybe you should take a look at Redux.
If you want to use it anywhere, create a variable that stores and uses global variables.
global.js
let users_id = "";
...
function set_users_id(data) {
users_id = data;
}
function get_users_id() {
return users_id;
}
Usage
import * as global from "filepath/global.js"
...
let user_id = data.user[0].user_id
global.set_users_id(user_id)
import * as global from "filepath/global.js"
alert(global.user_id) // return 1
alert(global.get_users_id()) // return 1
Related
I am using rtk-query and an axiosbasequery set up like this:
export const apiSlice = createApi({
reducerPath: "apiSlice",
baseQuery: baseQueryWithErrorHandling,
endpoints: (builder) => ({
//endpoints
})
})
baseQueryWithErrorHandling just logs out the app in the event of a 401 error.
export const baseQueryWithErrorHandling = async (
args: IBaseQuery,
api: BaseQueryApi,
extraOptions: {}
) => {
const result = await rawBaseQuery(args, api, extraOptions);
if (result.error) {
if (result.error.status == 401) {
api.dispatch(logOut());
return result;
}
}
return result;
};
rawbaseQuery:
export const rawBaseQuery: BaseQueryFn<
IBaseQuery,
unknown,
FetchBaseQueryError
> = async ({ url, method, data, params }, api, extraOptions) => {
const query = axiosBaseQuery({
baseUrl: Globals.URLS.BASE_URL,
headers: (headers) => {
headers["Accept"] = "application/json";
headers["Content-Type"] = "application/json";
return headers;
},
});
return query({ url, method, data, params }, api, extraOptions);
};
And finally, the actual axios query. I put withCredentials in two spots.
import type { BaseQueryFn, FetchBaseQueryError } from "#reduxjs/toolkit/query";
import axios from "axios";
import type { AxiosRequestConfig, AxiosError } from "axios";
import Globals from "../globals/Globals";
axios.defaults.withCredentials = true; // Here (Spot #1)
export interface IAxiosBaseQuery {
baseUrl?: string;
headers?: (headers: { [key: string]: string }) => { [key: string]: string };
}
export interface IBaseQuery {
url: string;
params?: { [key: string]: string | number | Boolean };
method: AxiosRequestConfig["method"];
data?: AxiosRequestConfig["data"];
error?: {
status: number;
data: unknown;
};
}
export const axiosBaseQuery = ({
baseUrl = "",
headers,
}: IAxiosBaseQuery): BaseQueryFn<
IBaseQuery,
unknown,
FetchBaseQueryError
> => async ({ url, method, data, params }, api, extraOptions) => {
try {
const result = await axios({
url: params?.skipBaseURL ? url : baseUrl + url,
method,
...(params && { params: params }),
...(headers && { headers: headers({}) }),
...(data && { data: data }),
responseType: "json",
withCredentials: true, // And here (Spot #2)
});
return { data: result.data };
} catch (axiosError) {
let err = axiosError as AxiosError;
// error logic
}
};
Yet, it seems sometimes the cookie is passed, and sometimes not.
Here's my flipper log of a successful request with a connect.sid in the cookie.
Yet, the next request results in an error because the session id doesn't exist.
Any suggestions? I've been having this problem for a week.
I wish to save the UserId when logging in, however, I cannot access the store using this.$store from the store itself, presumably because it is not a Vue component but a JS file.
EDIT: Solution based on an anwer in the code below
export default createStore({
state: {
user: null,
userId: null
},
mutations: {
setUser(state, user) {
state.user = user;
console.log("User set in store");
},
setUserId(state, userId) {
state.userId = userId;
console.log("User ID set in store");
}
},
getters: {
getUser: state => {
console.log('Retrieving user...')
return state.user;
}
},
actions: {
async login(store, credentials) {
let response = await(await fetch("http://localhost:4000/api/login", {
method: "POST",
body: JSON.stringify(credentials),
credentials: "include",
})).json();
store.commit('setUserId', response.userId);
},
},
});```
Your actions have access to the store reference via parameter async login(store, credentials)
So you can call the mutation setUserId from store reference when you get a response
.then(function (response) {
store.commit('setUserId', response.json().id);
})
I'm sending form data from React Hook Form to Netlify via their submission-created function. I don't have any problem with encoding individual form field values, but now I'm trying to encode an array of objects.
Here is an example of my form data:
{
_id: "12345-67890-asdf-qwer",
language: "Spanish",
formId: "add-registration-form",
got-ya: "",
classType: "Private lessons",
size: "1",
days: [
{
day: "Monday",
start: 08:00",
end: "09:30"
},
{
day: "Wednesday",
start: "08:00",
end: "09:30"
}
]
}
The only problem I have is with the "days" array. I've tried various ways to encode this and this is the function I've currently been working with (which isn't ideal):
const encode = (data) => {
return Object.keys(data).map(key => {
let val = data[key]
if (val !== null && typeof val === 'object') val = encode(val)
return `${key}=${encodeURIComponent(`${val}`.replace(/\s/g, '_'))}`
}).join('&')
}
I tried using a library like qs to stringify the data, but I can't figure out how to make that work.
And here is the function posting the data to Netlify:
// Handles the post process to Netlify so I can access their serverless functions
const handlePost = (formData, event) => {
event.preventDefault()
fetch(`/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": 'add-registration-form', ...formData }),
})
.then((response) => {
if(response.status === 200) {
navigate("../../")
} else {
alert("ERROR!")
}
console.log(response)
})
.catch((error) => {
setFormStatus("error")
console.log(error)
})
}
Finally, here is a sample of my submission-created file to receive and parse the encoded data:
const sanityClient = require("#sanity/client")
const client = sanityClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
token: process.env.SANITY_FORM_SUBMIT_TOKEN,
useCDN: false,
})
const { nanoid } = require('nanoid');
exports.handler = async function (event, context, callback) {
// Pulling out the payload from the body
const { payload } = JSON.parse(event.body)
// Checking which form has been submitted
const isAddRegistrationForm = payload.data.formId === "add-registration-form"
// Build the document JSON and submit it to SANITY
if (isAddRegistrationForm) {
// How do I decode the "days" data from payload?
let schedule = payload.data.days.map(d => (
{
_key: nanoid(),
_type: "classDayTime",
day: d.day,
time: {
_type: "timeRange",
start: d.start,
end: d.end
}
}
))
const addRegistrationForm = {
_type: "addRegistrationForm",
_studentId: payload.data._id,
classType: payload.data.classType,
schedule: schedule,
language: payload.data.language,
classSize: payload.data.size,
}
const result = await client.create(addRegistrationForm).catch((err) => console.log(err))
}
callback(null, {
statusCode: 200,
})
}
So, how do I properly encode my form data with a nested array of objects before sending it to Netlify? And then in the Netlify function how do I parse / decode that data to be able to submit it to Sanity?
So, the qs library proved to be my savior after all. I just wasn't implementing it correctly before. So, with the same form data structure, just make sure to import qs to your form component file:
import qs from 'qs'
and then make your encode function nice and succinct with:
// Transforms the form data from the React Hook Form output to a format Netlify can read
const encode = (data) => {
return qs.stringify(data)
}
Next, use this encode function in your handle submit function for the form:
// Handles the post process to Netlify so we can access their serverless functions
const handlePost = (formData, event) => {
event.preventDefault()
fetch(`/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": 'add-registration-form', ...formData }),
})
.then((response) => {
reset()
if(response.status === 200) {
alert("SUCCESS!")
} else {
alert("ERROR!")
}
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
Finally, this is what your Netlify submission-created.js file should look like more or less:
const sanityClient = require("#sanity/client")
const client = sanityClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
token: process.env.SANITY_FORM_SUBMIT_TOKEN,
useCDN: false,
})
const qs = require('qs')
const { nanoid } = require('nanoid');
exports.handler = async function (event, context, callback) {
// Pulling out the payload from the body
const { payload } = JSON.parse(event.body)
// Checking which form has been submitted
const isAddRegistrationForm = payload.data.formId === "add-registration-form"
// Build the document JSON and submit it to SANITY
if (isAddRegistrationForm) {
const parsedData = qs.parse(payload.data)
let schedule = parsedData.days
.map(d => (
{
_key: nanoid(),
_type: "classDayTime",
day: d.day,
time: {
_type: "timeRange",
start: d.start,
end: d.end
}
}
))
const addRegistrationForm = {
_type: "addRegistrationForm",
submitDate: new Date().toISOString(),
_studentId: parsedData._id,
classType: parsedData.classType,
schedule: schedule,
language: parsedData.language,
classSize: parsedData.size,
}
const result = await client.create(addRegistrationForm).catch((err) => console.log(err))
}
callback(null, {
statusCode: 200,
})
}
I am getting data from API.I need to push that data to a class.Below is my basic class structure:
Attendance.js
class Attendance{
constructor(SessionDate,SubjectName,Att){
this.SessionDate = SessionDate;
this.SubjectName = SessionDate+'-'+SubjectName;
this.Att = Att;
}
}
export default Attendance ;
Here is my Action class:
attendance.js
import Attendance from "../../models/Attendance";
import {AsyncStorage} from 'react-native';
export const SET_STUDENT_ATTENDANCE = 'SET_SET_STUDENT_ATTENDANCE';
export const fetchStudentAttendance = (newDate) => {
return async (dispatch,getState) =>{
const userData = await AsyncStorage.getItem('userData');
const transformedData = JSON.parse(userData);
const { token } = transformedData;
const Date = newDate;
try{const response = await fetch(
`http://........./api/stud/Get_Stud_Attendance_Details?Date=${Date}`,
{
headers: {
'Content-Type': 'application/json',
'Authorization':token
},
}
);
const resData = await response.json();
console.log(resData);
const loadedStudentAtt = [];
loadedStudentAtt.push(new Attendance(
resData["WeeklyAttendanceList"].SessionDate,
resData["WeeklyAttendanceList"].SubjectAbbr,
resData["WeeklyAttendanceList"].Att,
));
console.log(loadedStudentAtt);
dispatch({type: SET_STUDENT_ATTENDANCE,studentattendance:loadedStudentAtt});
}
catch(err){
console.log(err);
throw err;
};
};
};
Below is the sample API data:
Object {
"Error": null,
"Response": null,
"StartDate": "2020-02-04T00:00:00",
"StudentAttendancePercentList": Array [],
"Successful": true,
"WeeklyAttendanceList": Array [
Object {
"Att": "1",
"SessionDate": "28 Jan 2020",
"SessionDayName": "",
"SessionNo": 1,
"SessionTiming": "09:15 - 10:30",
"SubjectAbbr": "Subject1",
},
Object {
"Att": "0",
"SessionDate": "28 Jan 2020",
"SessionDayName": "",
"SessionNo": 1,
"SessionTiming": "09:15 - 10:30",
"SubjectAbbr": "Subject2",
},
],
}
The array that I am getting in console.log() is as below:
Array [
Attendance {
"Att": undefined,
"SessionDate": undefined,
"SubjectName": "undefined-undefined",
},
]
Can you please tell am I pushing the data correctly to the class?
Thanks in Advance.
WeeklyAttendanceList is Array of Objects. So you have to iterate over it and push that data into loadedStudentAtt.
const resData = await response.json();
console.log(resData);
const WeeklyAttendanceList = resData.WeeklyAttendanceList;
const loadedStudentAtt = [];
WeeklyAttendanceList.forEach(item => {
loadedStudentAtt.push(new Attendance(
item.SessionDate,
item.SubjectAbbr,
item.Att,
))
})
console.log(loadedStudentAtt);
I have a Nuxt app with many request to the same API, but also i need to make request to different providers apart of my main API and i don't know how to manage the default headers.
This is my working setup create a plugin to add the headers to all the request like this:
plugins/axios.js
export default function({ $axios, store, redirect }) {
$axios.onRequest(config => {
config.headers.common.Authorization = 'token 123';
config.headers.common["Custom-header"] = 'blablabla';
}
}
nuxt.config.js
module.exports = {
plugins: ["#/plugins/axios"],
axios: {
baseURL: process.env.API_URL,
}
}
store.js
async changeKeyVersionOnline({ commit }) {
const response = await this.$axios.get(
`users/1`
);
return response;
},
This works great for the main API but the problem is i need also to make request to other endpoints of third party service provider and of course the headers should be different.
How can i do that, i read about the proxy option of the nuxt-axios package but what i understand is this only changes the request base URL, i cant find how to set different headers to a specific request.
My final solution was based on create some actions in a central store so the axios requests are made trough this actions.
central.js (Where the axios related actions live)
import qs from "qs";
export const state = () => ({
accessToken: "",
clientId: 0
});
export const getters = {
getHeadersWithAuth: state => {
const config = {
headers: {
Authorization: "Bearer " + state.accessToken
}
};
return config;
},
getHeadersWithAuthClient: state => {
const config = {
headers: {
Authorization: "Bearer " + state.accessToken,
Client: state.clientId
}
};
return config;
}
};
export const mutations = {};
export const actions = {
async getWithAuth({ getters }, { path, params }) {
const config = getters.getHeadersWithAuth;
config.params = params;
config.paramsSerializer = function(params) {
return qs.stringify(params, { encode: false });
};
const result = await this.$axios.get(path, config);
return result;
},
async getWithAuthClient({ getters }, { path, params }) {
const config = getters.getHeadersWithAuthClient;
config.params = params;
config.paramsSerializer = function(params) {
return qs.stringify(params, { encode: false });
};
const result = await this.$axios.get(path, config);
return result;
},
async putWithAuthClient({ getters }, { path, body, params }) {
const config = getters.getHeadersWithAuthClient;
config.params = params;
config.paramsSerializer = function(params) {
return qs.stringify(params, { encode: false });
};
const result = await this.$axios.put(path, body, config);
return result;
}
};
test.js Other store which use the custom axios requests
async updateProductDetailsAction({ commit, dispatch, state }, productData) {
const request = {
path: `endpoints/` + productData.id + `/details`,
body: {
length: 123,
name: 'The product name'
},
params: {}
};
const result = await dispatch("auth/putWithAuthClient", request, {
root: true
});
await commit("setProductDetails", productData.id);
return result;
}