I have a piece of code and a variable sometimes comes as undefined but I need to validate if that value is undefined to pass the execution of code
the validation I provided is not solving the problem
_getKeycodeScans = (data) => this.props.getKeycodeScans(data.keycode.uid, 1).then(() => {
this.setState({detailsModalVisible: true, homeDetails: data});
}).catch(error => {
debugger
const { serverError } = JSON.parse(error.message);
this.setState({ serverError, loading: false });
});
_openDetailsModal = (data) => () => Promise.all([
console.log('&&&&&&&&&&&&&&&&&&&&**********&&&&&&&&&&&&&&&&&&&&&'),
console.log(data),
this._getKeycodeScans(data),
this._getKeycodeImageDataUrl(data),
this._getHomes(data)
]);
When the _openDetailsModal gets hit and it calls the functions inside and the uid is undefined.
I get the error message: TypeError: Cannot read property 'uid' of undefined.
When uid is undefined I actually don't need the data
If your goal is to only continue executing your script if data.keycode.uid is not undefined, you could just:
_getKeycodeScans = (data) => {
if(!data.keycode || data.keycode.uid === undefined) {
return;
}
return this.props.getKeycodeScans(data.keycode.uid, 1).then(() => {
this.setState({detailsModalVisible: true, homeDetails: data});
}).catch(error => {
const { serverError } = JSON.parse(error.message);
this.setState({ serverError, loading: false });
});
}
Related
For example, I can't access to this module, why ?
let nodeCacheClient;
module.exports = {
initNodeCache: () => {
const NodeCache = require("node-cache");
nodeCacheClient = new NodeCache();
return nodeCacheClient;
},
insertToCacheWithTtl: (key, obj, ttl) => {
return nodeCacheClient.set(key, obj, ttl);
},
getCache: (key) => {
return nodeCacheClient.get(key);
},
deleteKey: (key) => {
return nodeCacheClient.del(key);
},
};
when I run this test I get this : TypeError: Cannot read property 'get' of undefined Error
test("login a user", async () => {
try {
const response = await axiosInstance.post("users/login", {
email: "test#gmail.com",
password: "144847120",
otpCode: getCacheClient.getCache("test#gmail.com")
});
console.log(response.data);
expect(response.data.status).toBe("success");
} catch (error) {
console.log(error + " Error");
expect(error);
}
});
It’s totally normal!
Actually you got access to your module, and the error is coming into your module where the “nodeCacheClient” is undefined since it was not defined!
Your error is coming from your “getCache()” function, in this syntax:
return nodeCacheClient.get(key);
Where in your test you didnt call for the “initNodeCache()” method which will do
nodeCacheClient = new NodeCache();
So, for your test scope, the nodeCacheClient is undefined, and that’s why
nodeCacheClient.get(key);
Will return the
typeError: Cannot read property 'get' of undefined Error
I do an axios get(url + this.state.user) but the parameter is undefined for no reason because when i do a console log of the parameter it exists...
My code
state = {
user: [],
taches : [],
loading: false
}
componentDidMount = () => {
this.setState({loading:true})
axios.get('/get-user').then(response => {
this.setState({user : response.data});
}).catch(error => {
console.log(error);
})
axios.get('/get-taches/' + this.state.user.ID_Users).then(response => {
console.log(this.state.user.ID_Users);
}).catch(error => {
console.log(this.state.user.ID_Users);
console.log(error);
})
}
The parameter of axios get-taches return undefined but when i do a console log of it in the catch error it is defined and it shows in the console... I dont know where the problem is.
Thank you for your help
I'm trying to catch the error this error message from my Rest controller in spring
#GetMapping
public List<Student> getAllStudent() {
throw new IllegalStateException("Opps can not get all students");
// return studentService.getAllStudents();
}
The error is catch in react this way, what I'm trying to do is to show in the console the Error message
import fetch from "unfetch";
const checkStatus = (response) => {
if (response.ok) {
return response;
} else {
let error = new Error(response.statusText);
error.response = response;
response.json().then((e) => {
error.error = e;
});
return Promise.reject(error);
}
};
export const getAllStudents = () =>
fetch("http://localhost:1020/api/students").then(checkStatus);
And then is consume by this method to show it in the console
const fetchAllStudents = () => {
this.setState({
isFetching: true,
});
getAllStudents()
.then((res) =>
res.json().then((students) => {
console.log(students);
this.setState({
students,
isFetching: false,
});
})
)
.catch((error) => {
console.log(error.error.message);
// const message =error.error.message;
// errorNotification(message,message)
this.setState({
isFetching: false,
});
});
};
The problem is that I get is that "message" is undefined I want to log "Opps can not get all students" in the console:
Add this line to your application.properties file:
server.error.include-message=always
And try throwing ResponseStatusException, so that you give a HTTP Status, together with the message, and not just 500 Server Error.
Like this:
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Your Message...");
Here i have my component code for SignIng Up user and check for Error. At first error is null.
let error = useSelector((state) => state.authReducer.error);
const checkErrorLoading = () => {
console.log("If error found"); //At first it gives null, but on backend there is error
toast.error(error);
console.log(loading, error);
};
const handleSubmit = async (e) => {
if (isSignup) {
dispatch(signup(form, history));
checkErrorLoading();
} else {
dispatch(signin(form, history));
checkErrorLoading();
}
};
Now at my singupForm, i provide wrong input or wrong data. The backend gives me error that is completely fine.
ISSUE => But when i click on Login button. At first attempt it does not provide any error message. After second attempt it works fine, but not at first attempt. At first attempt it gives me Error value NULL while there is still an error
Here is my action.
export const signup = (formData, history) => async (dispatch) => {
try {
const res = await api.signUp(formData);
dispatch({ type: authConstants.AUTH_REQUEST });
if (res.status === 200) {
const { data } = res;
console.log(data);
dispatch({
type: authConstants.AUTH_SUCCESS,
payload: data,
});
}
console.log(res.status);
history.push("/");
} catch (error) {
console.log(error.response);
dispatch({
type: authConstants.AUTH_FAILURE,
payload: error.response.data.error,
});
}
};
and than reducer.
const initialState = {
authData: null,
error: null,
loading: false,
};
const authReducer = (state = initialState, action) => {
switch (action.type) {
case authConstants.AUTH_REQUEST:
return { ...state, loading: true, error: null };
case authConstants.AUTH_SUCCESS:
localStorage.setItem("profile", JSON.stringify({ ...action?.payload }));
return { ...state, authData: action?.data, loading: false, error: null };
case authConstants.AUTH_FAILURE:
console.log(action.payload);
return { ...state, loading: false, error: action.payload };
}
You should use useEffect instead of local function (checkErrorLoading ) for such cases:
useEffect(() => {
console.log("If error found");
toast.error(error);
console.log(loading, error);
},[error]);
Currently what you doing is creating local function that closures error variable, which initially is null + state is updated asynchronously, so you cannot execute function right after dispatching (even if variable wouldn't be closured, you will not have fresh state there)
I'm trying to display data from my web using API. My API is working correctly. But some how i face this issue json.data is not a function. (In 'json.data()', 'json.data' is an instance of Array)]. Can I anyone help me on this?
_loadInitialState = async () => {
const token = await AsyncStorage.getItem('token');
const myArray = await AsyncStorage.getItem('language_type');
_onSetLanguage(myArray)
var loadAll = this.props.navigation.getParam('loadAll');
if (loadAll == true) { this.setState({ isLoading: true }) }
var have_access = this.props.navigation.getParam('have_access');
if (have_access != undefined) { this.setState({ have_access: have_access }) }
if (staticData.get_centre_settings() != null) { this.setState({ have_access: true }) }
let today = Moment();
this.setState({
today: Moment(today).format('YYYY-MM-DD'),
})
// alert(FetchURL.get_baseURL() + "leave?centre_id=" + staticData.get_centre_settings().centre.centre_id)
// alert(token)
// return
fetch(FetchURL.get_baseURL() + "leave?centre_id=" + staticData.get_centre_settings().centre.centre_id, {
method: 'GET',
headers: {
'Authorization': 'Bearer '+ token,
}
})
.then(response => response.json())
.then((json) => {
// alert(json)
if (json.error) {
alert(json.error);
} else {
this.setState({
staffLeave: json.data(),
isLoading: false
});
}
})
.catch((err) => {
console.log(err)
alert(err)
// alert(strings.data_fail);
})
this.setState({ view_access: true })
}
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
You have the response after response.json() as json. If you want to store it to state, use json.data and not json.data(), just as you check for json.error.
When you read the error json.data is not a function. (In 'json.data()', 'json.data' is an instance of Array)]
What this is telling you is that json.data is not a callable function. Therefore json.data() will not work. json.data is an array per the error message. You would access some part of that by: json.data[0] But you'd want to check the length of that array and understand the type (which Typescript helps solve).
// alert(json)
if (json.error) {
alert(json.error);
} else {
this.setState({
staffLeave: json.data(),
isLoading: false
});
}
Replace with
if (json.error) {
alert(json.error);
} else {
this.setState({
staffLeave: json.data,
isLoading: false
});
}
hopefully, it's work.