to everyone, i have a problem about a request to the server. I get error 400, but i don't understand where is the problem, i checked my code thousand times and it looks like all good.
Basically, with this request i get the "order number".
This is the reducer:
const initialState = {
status: "STALE",
};
export const orderObjectReducer = (state = initialState, action) => {
if (action.type === "SEND_ORDER_FAILED") {
return { status: "FAILED" };
}
if (action.type === "SEND_ORDER_IS_LOADING") {
return {
status: "LOADING",
};
}
if (action.type === "SEND_ORDER_STALE") {
return {
status: "STALE",
};
}
if (action.type === "SEND_ORDER_SUCCESS") {
return {
status: "SUCCESS",
data: action.payload,
};
}
return state;
};
export const makeOrder = (ingredientsIds) => async (dispatch) => {
dispatch({
type: "SEND_ORDER_IS_LOADING",
});
const result = await fetch("https://norma.nomoreparties.space/api/orders", {
method: "POST",
body: JSON.stringify({ ingredients: ingredientsIds }),
})
.then((res) => res.json())
.catch(() => null);
if (!result || !result.success) {
dispatch({
type: "SEND_ORDER_FAILED",
});
return result;
}
dispatch({
type: "SEND_ORDER_SUCCESS",
payload: result,
});
};
The button that trigger the request:
<Button
disabled={selectedIngredientsIds.length === 0}
htmlType="button"
onClick={() => dispatch(makeOrder(selectedIngredientsIds))}
type="primary"
size="large"
extraClass="mr-4" >
Оформить заказ
</Button>
This is the component that get the result of the request:
export const OrderDetails = () => {
const { status, data } = useAppSelector((store) => store.orderObject);
const dispatch = useAppDispatch();
if (status === "STALE" || status === "LOADING") {
return null;
}
return (
<Modal onClose={() => dispatch({ type: "SEND_ORDER_STALE" })}>
{status === "FAILED" ? ("Ошибка") : (
<>
<p className={`${orderDetailsStyle.orderDetails__orderNumber} text text_type_digits-large mt-30 mb-8`}>{data?.order.number}</p>
<p className="text text_type_main-medium mb-15">идентификатор заказа</p>
<img src={done} alt="заказано" className={orderDetailsStyle.orderDetails__image}/>
<p className="text text_type_main-default mb-2">Ваш заказ начали готовить</p>
<p className="text text_type_main-default text_color_inactive mb-30">Дождитесь готовности на орбитальной станции</p>
</>
)}
</Modal>
);
};
How can i solve the problem?
A 400 Bad Request simply means the request was bad. The server is saying something is wrong with what you sent it.
To test this outside of your app, in Firefox I use a free extension called RESTED Client to simply test a POST to your URL (https://norma.nomoreparties.space/api/orders) with the a pseudo body of { ingredients: ["1", "2"]}. It returns the following:
{
"success": false,
"message": "Ingredient ids must be provided"
}
The problem is with the data you are sending. The reason I know this is because I repeated exactly what your app is doing here:
const result = await fetch("https://norma.nomoreparties.space/api/orders", {
method: "POST",
body: JSON.stringify({ ingredients: ingredientsIds }),
})
the code is right, i needed just to add to my request:
headers: {
"Content-Type": "application/json",
},
First I apologize for my English. I have been working on React to native applications for 4 months. But sometimes I get this error and don't mind.
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method,
in CustomerDetailScreen (at SceneView.tsx:123)
This is because when I click the button, I open a screen, and when the screen is not fully loaded I press the back button. How can I resolve this warning? I'll show you some sample code examples.
I hope I could explain. Can you help me with this topic? I want to fully understand the logic. I've read something called AbortController in some articles but I don't know exactly.
constructor(props) {
super(props);
this._isMounted = false;
this.state = {
id: props.route.params.id,
username: '',
token: null,
cityId: 1,
townId: 1,
cityData: [],
townData: [],
selectedIndex: 0,
selectedCity: new IndexPath(0),
selectedTown: new IndexPath(0),
}
}
componentDidMount() {
this._isMounted = true;
this._isMounted && this._getToken();
}
componentWillUnmount() {
this._isMounted = false;
}
_getToken = async () => {
try {
const username = await AsyncStorage.getItem('username');
const token = await AsyncStorage.getItem('token');
if(token === null) {
await AsyncStorage.removeItem('token');
}else {
this.setState({ username: username, token: token });
this._isMounted && this.loadCustomerDetail();
}
} catch (error) {
console.log(error);
}
};
loadCustomerDetail() {
try {
const { username, token } = this.state;
if(token) {
const { id } = this.state;
var credentials = Base64.btoa(username + ':' + token);
var URL = `https://portal.xxxxxx.com/api/v1/Customer/${id}`;
axios.get(URL, {headers : { 'Espo-Authorization' : credentials }})
.then(this.dataSuccess.bind(this))
.catch(this.dataFail.bind(this));
}
}catch (err) {
console.log(err);
}
};
dataSuccess(response) {
this.setState({
isLoading: false,
cityId: response.data.cityId,
townId: response.data.townId
}, () => {
this.getCities();
});
}
getCities() {
const { username, token, cityId } = this.state;
let credentials = Base64.btoa(username + ':' + token);
axios.get('https://portal.xxxxx.com/api/v1/Cities', { headers : { 'Espo-Authorization' : credentials }})
.then((response) => {
response.data.list.sort(function(a, b) {
return Number(a.id) > Number(b.id);
});
this.setState({cityData: response.data.list}, () => {
this.setState({ selectedCity: new IndexPath(this.state.cityData[cityId-1].id - 1) });
this.getTowns(this.state.cityData[cityId-1].id);
});
}).catch((error) => {
console.log(error);
});
}
getTowns(cityId) {
this.setState({ townLoading: true });
const { username, token } = this.state;
let credentials = Base64.btoa(username + ':' + token);
axios.get(`https://portal.xxxxx.com/api/v1/Towns/action/TownList?cityId=${cityId}`, { headers : { 'Espo-Authorization' : credentials }})
.then((response) => {
this.setState({ townData: response.data, townLoading: false }, () => {
for (const [key, value] of Object.entries(this.state.townData)) {
if(value.id === this.state.townId) {
this.setState({ selectedTown: new IndexPath(key) })
}
}
});
}).catch((error) => {
console.log(error);
});
}
An example area:
this.setState({ username: username, token: token });
this._isMounted && this.loadCustomerDetail();
You can see that setState will be called even if the component is no longer mounted.
Fix
Ensure component is mounted before changing state:
if (this._isMounted) {
this.setState({ username: username, token: token });
this.loadCustomerDetail();
}
I would like to explain my problem of the day.
i think it's harder than usual, so let me explain
here i start by getting a get
getRandom = async () => {
const res = await axios.get(
entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}
here is my method for delete
handleSubmit = (e) => {
e.preventDefault();
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
}
then I map it
render() {
let datas = this.state.data.map((datass, index) => {
return (
<Col sm="12" key={index}>
<form onSubmit={this.handleSubmit}>
<button type="submit">Delete</button>
</form>
<div>{datass.name}</div>
</Col>
then i return the result on my map
return (
<div>
{datas}
</div>
so works correctly ,
but the problem is the following when I want to delete only 1 CARD it deletes all my BDD
Here is my routes on BDD
app.delete('/api/alluserpls', (req, res, ) => {
const formData = req.body;
connection.query('DELETE FROM alluserpls SET ?', formData, err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
I would like that when I click on delete it only deletes the card and not all of my database.
How can I fix this issue?
Here is one way to do it, assign the id of the user to button id attribute field and then call the delete API with the user id
handleSubmit = (e, id) => {
e.preventDefault();
const userIdData = { id };
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userIdData),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
, in the render method you can pass the id as variable to the handleSubmit function
render() {
let datas = this.state.data.map((datass, index) => {
return (
<Col sm="12" key={index}>
<form onSubmit={(e) => this.handleSubmit(e, datass.id)}>
<button type="submit">Delete</button>
</form>
<div>{datass.name}</div>
</Col>
and in the backend you can get the id and delete only the particular user
app.delete('/api/alluserpls', (req, res, ) => {
const formData = req.body;
const userId = req.body.id;
const deleteQuery = `DELETE from alluserpls WHERE id = ${userId}`;
connection.query(deleteQuery, err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
Can't seem to resolve this error.
TypeError
For the function to work the user is supposed to be able to add songs to a 'New Playlist' and then save that playlist.
The app seems to work fine until you click the button to save the playlist at which point all you see is this error.
Trying to access this component:
const clientId = "783dbc97776940e28f307dfc902ad41b";
const redirectUri = "http//localhost:3000/";
let accessToken;
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
// check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
// This clears the parameters, allowing us to grab a new access token when it expires.
window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
window.history.pushState("Access Token", null, "/");
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
})
.then(response => {
return response.json();
})
.then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
});
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userId;
return fetch("https://api.spotify.com/v1/me", { headers: headers })
.then(response => response.json())
.then(jsonResponse => {
userId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
headers: headers,
method: "POST",
body: JSON.stringify({ name: name })
})
.then(response => response.json())
.then(jsonResponse => {
const playlistId = jsonResponse.id;
return fetch(
`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`,
{
headers: headers,
method: "POST",
body: JSON.stringify({ uris: trackUris })
}
);
});
});
}
};
export default Spotify;
For use here:
import React from 'react';
import './App.css';
import SearchBar from '../SearchBar/SearchBar';
import SearchResults from '../SearchResults/SearchResults';
import Playlist from '../Playlist/Playlist';
import Spotify from '../../util/Spotify';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
searchResults: [],
playlistName: 'My Playlist',
playlistTracks: []
}
this.addTrack = this.addTrack.bind(this);
this.removeTrack = this.removeTrack.bind(this);
this.updatePlaylistName = this.updatePlaylistName.bind(this);
this.savePlaylist = this.savePlaylist.bind(this);
this.search = this.search.bind(this);
}
addTrack(track) {
if (this.state.playlistTracks.find(savedTrack => savedTrack.id === track.id)) {
return;
}
this.state.playlistTracks.push(track);
this.setState({playlistTracks: this.state.playlistTracks})
}
removeTrack(track) {
this.setState.playlistTracks = this.state.playlistTracks.filter(currentTrack => currentTrack.id !== track.id)
this.setState({playlistTracks: this.state.playlistTracks})
}
updatePlaylistName(name) {
this.setState({playlistName: name});
}
savePlaylist() {
const trackUris = this.state.playlistTracks.map(track => track.uri);
Spotify.savePlaylist(this.state.playlistName, trackUris).then(() => {
this.setState({
playlistName: 'New Playlist',
playlistTracks: []
})
})
}
search(term) {
Spotify.search(term).then(searchResults => {
this.setState({searchResults: searchResults})
})
}
render() {
return (
<div>
<h1>Ja<span className="highlight">mmm</span>ing</h1>
<div className="App">
<SearchBar onSearch={this.search} />
<div className="App-playlist">
<SearchResults searchResults={this.state.searchResults} onAdd={this.addTrack} />
<Playlist playlistName={this.state.playlistName} playlistTracks={this.state.playlistTracks} onRemove={this.removeTrack} onNameChange={this.updatePlaylistName} onSave={this.savePlaylist} />
</div>
</div>
</div>
)
}
}
// if(typeof(App.savePlaylist) == 'undefined') {
// console.log('whoops')
// }
export default App;
Any ideas why?
I'm very new to this and am completely lost as to why this is happening.
You need to return a Promise for when the input is not right:
if (!name || !trackUris.length) {
return Promise.resolve();
};
Also, don't change variables of the state object. Don't do this:
this.state.playlistTracks.push(track);
this.setState({playlistTracks: this.state.playlistTracks})
Instead, do this:
this.setState({playlistTracks: [...this.state.playlistTracks, track]})
In you code when the following if condition is true, you're not returning a promise.
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
// What you can do instead
// return Promise.reject();
};
....
...
Simply returning return; will return undefined and trying to access then on it will throw error.
I am building a React app and it uses Axios. The issue is this was working for the last month and now all of a sudden it stopped working. This error makes no sense to me because it was previously working.
The error states Unhandled Rejection (TypeError): api.getUser is not a function
Here is the file containing axios, api.js:
import axios from 'axios';
import key from './keys';
import URL from './url';
export function login() {
let url = URL + '/helix/login/';
return axios.get(url, {headers: {'Api-Key': key}}).then(res => {
window.location = res.data.authorization_url;
});
}
export function authLogin(data) {
let url = URL + '/helix/socialauth/login/';
return axios.post(url, data, {headers: {'Api-Key': key}}).then(res => res);
}
export function consent(data, header) {
let url = URL + '/user/profile/';
return axios.put(url, data, {headers: header}).then(res => res);
}
export function getUser(header) {
let url = URL + '/user/profile/';
return axios.get(url, {headers: header}).then(res => res);
}
export function updateUser(data, header) {
let url = URL + '/user/profile/';
return axios.put(url, data, {headers: header}).then(res => res);
}
export function getAcct(header) {
let url = URL + '/helix/account/';
return axios.get(url, {headers: header}).then(res => res);
}
export function getTraits(header) {
let url = URL + '/genomics/traits/summary/';
return axios.get(url, {headers: header}).then(res => res);
}
export function getTraitDetails(header, id) {
let url = URL + '/genomics/traits/' + id + '/';
return axios.get(url, {headers: header}).then(res => res);
}
export function getCancers(header) {
let url = URL + '/genomics/explore/';
return axios.get(url, {headers: header}).then(res => res);
}
export function getGenomics(header) {
let url = URL + '/genomics/home/';
return axios.get(url, {headers: header}).then(res => res);
}
export default {login, authLogin, consent, getUser, updateUser, getAcct, getTraits, getTraitDetails, getCancers, getGenomics};
Here is the file that is using these files, it is part of the Context API from React 14, UserContext.js:
import React from 'react';
import moment from 'moment';
// Utilities
import apikey from '../config/keys';
import history from '../config/history';
const api = require('../config/api');
// Create a context with default values
export const UserContext = React.createContext({
first_name: null,
last_name: null,
email: null,
birthday: null,
gender: null,
access_token: null,
helix_user_id: null,
uuid: null,
key: null,
status: 'register',
loading: false,
accepted_terms: false,
delivery_date: null,
data_available: false,
kit_processing: false,
kit_registered: false,
traits_processed: false,
ldt_status: null,
userVisits: 0,
cancer_groups: null,
userTraits: [],
userVariants: false,
pos_trait_details: null,
pos_trait_user: null,
pos_trait_modules: null,
});
// This is the consumer of the values (state)
export const UserConsumer = UserContext.Consumer;
// Create a provider (wrapper that handles the logic)
// This also allows communication to context and update
// state values throughout app with user info
export class UserProvider extends React.Component {
constructor(props) {
super(props);
this.state = {
first_name: null,
last_name: null,
email: null,
birthday: null,
gender: null,
access_token: null,
helix_user_id: null,
uuid: null,
key: null,
status: 'register',
loading: false,
accepted_terms: false,
data_available: false,
delivery_date: null,
kit_processing: false,
kit_registered: false,
traits_processed: false,
ldt_status: null,
userVisits: 0,
cancer_groups: [],
userTraits: [],
userVariants: false,
pos_trait_details: [],
pos_trait_user: null,
pos_trait_modules_0: null,
pos_trait_modules_1: null,
pos_trait_modules_2: null,
pos_trait_modules_3: null,
pos_trait_modules_4: null,
pos_trait_modules_5: null,
pos_trait_modules_6: null,
};
this.get = this.get.bind(this);
this.update = this.update.bind(this);
this.updateConsent = this.updateConsent.bind(this);
this.getAccount = this.getAccount.bind(this);
this.logout = this.logout.bind(this);
this.checkUserVisits = this.checkUserVisits.bind(this);
this.getTraits = this.getTraits.bind(this);
this.checkLastVisit = this.checkLastVisit.bind(this);
this.getTraitDetails = this.getTraitDetails.bind(this);
}
componentDidMount() {
let revisit = localStorage.getItem('giraffeToken');
let test = 'state';
let location = window.location.href;
if(revisit !== null) {
this.checkLastVisit(revisit);
}
if(revisit === null &&
(location.includes('dashboard')
|| location.includes('profile')
|| location.includes('register')
|| location.includes('consent')
|| location.includes('gene')
|| location.includes('results-prep'))) {
this.setState({loading: true});
localStorage.removeItem('giraffeDate');
localStorage.removeItem('giraffeKey');
localStorage.removeItem('giraffeStatus');
localStorage.removeItem('giraffeToken');
setTimeout(() => {
this.setState({loading:false});
}, 1000);
history.push('/');
window.location.reload();
}
if(location.includes(test)) {
this.setState({loading: true});
let queryParams = location.split('?')[1];
let params = queryParams.split('&');
let pair = null;
let code;
let state;
params.forEach(param => {
pair = param.split('=');
if(pair[0] === 'code') {
code = pair[1];
}
if(pair[0] === 'state') {
state = pair[1];
}
});
let data = {code: code, state: state};
api.authLogin(data).then(({data: {account, key, status}}) => {
this.setState({
key: key,
first_name: account.first_name,
last_name: account.last_name,
email: account.email,
access_token: account.access_token,
helix_user_id: account.helix_user_id,
uuid: account.uuid,
status: status,
loading: false
});
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + key
};
api.getUser(header).then(({data: {birthday, gender}}) => {
this.setState({
birthday: birthday,
gender: gender,
});
});
api.getCancers(header).then(({data: {cancer_groups}}) => {
this.setState({
cancer_groups: cancer_groups,
loading: false
})
});
api.getGenomics(header).then((data) => {
console.log(data)
})
let d = moment().format('x');
localStorage.setItem('giraffeToken', account.access_token);
localStorage.setItem('giraffeKey', key);
localStorage.setItem('giraffeDate', d);
localStorage.setItem('giraffeStatus', status);
history.push('/profile');
});
}
}
shouldComponentUpdate(nextProps, nextState) {
return true;
}
get() {
api.login();
}
update() {
let data = {
};
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + this.state.key
};
api.updateUser(data, header);
}
updateConsent() {
let data = {
accepted_terms: true
};
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + this.state.key
};
api.consent(data, header).then(({data: {accepted_terms}}) => {
this.setState({
accepted_terms: accepted_terms,
status: 'login',
loading: true
});
setTimeout(() => {
this.setState({loading: false});
history.push('/profile');
}, 1000);
});
}
getAccount() {
this.setState({loading: true});
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + this.state.key
};
api.getAcct(header).then(({data: {status: {data_available, kit_processing, kit_registered, traits_processed, ldt_status, delivery_date}}}) => {
this.setState({
delivery_date: delivery_date,
data_available: data_available,
kit_processing: kit_processing,
kit_registered: kit_registered,
traits_processed: traits_processed,
ldt_status: ldt_status,
});
this.checkUserVisits();
});
this.setState({loading: false});
}
checkUserVisits() {
if(this.state.data_available && this.state.kit_registered && this.state.kit_processing && this.state.traits_processed) {
let visits = localStorage.getItem('visits');
if(visits === null || visits === undefined) {
localStorage.setItem('visits', 0);
}
else if(visits === '0') {
let visit = parseInt(visits, 10);
localStorage.setItem('visits', (visit + 1));
this.setState({userVisits: (visit + 1)});
}
}
}
checkLastVisit(revisit) {
let lastLogin = parseInt(localStorage.getItem('giraffeDate'), 10);
let token = localStorage.getItem('giraffeKey');
let giraffeStatus = localStorage.getItem('giraffeStatus');
let now = moment();
if(now.diff(lastLogin, 'days') >= 1) {
this.setState({loading: true});
localStorage.removeItem('giraffeDate');
localStorage.removeItem('giraffeKey');
localStorage.removeItem('giraffeStatus');
localStorage.removeItem('giraffeToken');
setTimeout(() => {
this.setState({loading:false});
}, 1000);
history.push('/');
window.location.reload();
}
else {
this.setState({loading: true});
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + token
};
api.getAcct(header).then(({data, data: {first_name, last_name, email, helix_user_id, uuid, status}}) => {
this.setState({
access_token: localStorage.getItem('giraffeToken'),
key: token,
first_name: first_name,
last_name: last_name,
email: email,
helix_user_id: helix_user_id,
uuid: uuid,
status: giraffeStatus,
delivery_date: status.delivery_date,
data_available: status.data_available,
kit_processing: status.kit_processing,
kit_registered: status.kit_registered,
traits_processed: status.traits_processed,
ldt_status: status.ldt_status,
userVisits: parseInt(localStorage.getItem('visits'), 10)
});
}).catch((err) => {
console.log('acct err: ', err);
this.setState({loading: true});
localStorage.removeItem('giraffeDate');
localStorage.removeItem('giraffeKey');
localStorage.removeItem('giraffeStatus');
localStorage.removeItem('giraffeToken');
localStorage.removeItem('visits');
setTimeout(() => {
this.setState({loading:false});
}, 1000);
history.push('/');
window.location.reload();
});
api.getUser(header).then(({data: {birthday, gender}}) => {
this.setState({
birthday: birthday,
gender: gender,
});
});
api.getTraits(header).then(({data}) => {
let variant = data.filter(item => item.user_trait.genotype_sum > 0);
if(variant.length > 0) {
this.setState({
userTraits: data,
userVariants: true
});
}
else {
this.setState({
userTraits: []
});
}
}).catch((err) => {
console.log('traits error: ', err);
this.setState({loading: true});
localStorage.removeItem('giraffeDate');
localStorage.removeItem('giraffeKey');
localStorage.removeItem('giraffeStatus');
localStorage.removeItem('giraffeToken');
localStorage.removeItem('visits');
setTimeout(() => {
this.setState({loading:false});
}, 1000);
history.push('/');
window.location.reload();
});
api.getCancers(header).then(({data: {cancer_groups}}) => {
this.setState({
cancer_groups: cancer_groups
})
});
setTimeout(() => {
history.push('/profile');
this.setState({loading: false});
}, 1000);
}
}
getTraits() {
this.setState({loading: true});
// Get user results and based on results show the appropriate dashboard
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + this.state.key
};
api.getTraits(header).then(({data}) => {
let variant = data.filter(item => item.user_trait.genotype_sum > 0);
if(variant.length > 0) {
this.setState({
userTraits: data,
userVariants: true
});
}
else {
this.setState({
userTraits: []
});
}
});
setTimeout(() => {
this.setState({loading: false});
}, 1000);
}
logout() {
this.setState({loading: true});
localStorage.removeItem('giraffeDate');
localStorage.removeItem('giraffeKey');
localStorage.removeItem('giraffeStatus');
localStorage.removeItem('giraffeToken');
setTimeout(() => {
this.setState({loading:false});
}, 1000);
history.push('/');
window.location.reload();
}
getTraitDetails(id) {
let header = {
'Api-Key': apikey,
'Authorization': 'Token ' + this.state.key
};
api.getTraitDetails(header, id).then(({data: {modules, user_trait, trait}}) => {
this.setState({
pos_trait_details: trait,
pos_trait_user: user_trait,
pos_trait_modules: modules
});
for(let i = 0; i < modules.length; i ++) {
let name = 'pos_trait_modules_' + i;
let age_groups = 'pos_trait_modules_' + i + '_age_groups';
let body = 'pos_trait_modules_' + i + '_body';
let icon = 'pos_trait_modules_' + i + '_icon';
let image = 'pos_trait_modules_' + i + '_image';
let item_type = 'pos_trait_modules_' + i + '_item_type';
let title = 'pos_trait_modules_' + i + '_title';
let url = 'pos_trait_modules_' + i + '_url';
let url_title = 'pos_trait_modules_' + i + '_url_title';
let items = 'pos_trait_modules_' + i + '_items';
// console.log(Object.values(modules[i])[0]);
if(Object.values(modules[i])[0] !== null) {
this.setState({
[name]: Object.values(modules[i])[0],
[age_groups]: Object.values(modules[i])[0].age_groups,
[body]: Object.values(modules[i])[0].body,
[icon]: Object.values(modules[i])[0].icon,
[image]: Object.values(modules[i])[0].image,
[item_type]: Object.values(modules[i])[0].item_type,
[title]: Object.values(modules[i])[0].title,
[url]: Object.values(modules[i])[0].url,
[url_title]: Object.values(modules[i])[0].url_title,
[items]: Object.values(modules[i])[0].items
});
}
}
});
}
render() {
return (
<UserContext.Provider
value={{user: this.state,
get: this.get,
update: this.update,
updateConsent: this.updateConsent,
getAccount: this.getAccount,
logout: this.logout,
getTraits: this.getTraits,
getTraitDetails: this.getTraitDetails
}}
>
{this.props.children}
</UserContext.Provider>
);
}
}
I have spent the last hour trying to figure out the issue to no avail. Any help would be appreciated.
I have looked at how the export is happening or if something else is going on but couldn't find anything.
Thanks
Try this, change require from:
const api = require('../config/api');
To:
import * as api from '../config/api'
If doesn't work, put this console.log(api) just after that line, it might be an issue with your babel's version.