I'm trying to create my first angular/rxjs app and can't figure out why I'm getting this error:
TypeError: Cannot read property 'students' of undefined
I was trying to follow tutorial but I didn't copy it word by word.
I'm totally new to this.
https://dpaste.de/F415#L1,30,98,131
in your init function you have the following:
this.students$ = this.store.select(fromStore.getAllStudents);
now, this getAllStudents states as follow:
export const getAllStudents = createSelector(getStudentState, fromStudents.getStudents);
which means we are going to get something from getStudentState first, pass it to the fromStudents.getStudents, and return its returned value.
Let's see what the getStudendState function does:
export const getStudentState = createSelector(getState, (state: StudentsState) => state.students);
ok, again we take the state from the getState function and return the students property, let's analyze this getState:
export const getState = createFeatureSelector<StudentsState>('student-list');
Everything is clear now, we get the student-list property and we can travel back to our chain... unless...
export interface StudentsState {
students: fromStudents.StudentState;
}
as expected, when we get the student-list property from our state, it returns undefined since doesn't exist, and at that point, the getState will try to access state.students which will lead to the error you get.
Related
Having trouble handling the response from an HTTP request using Axios with TypeScript. I don't understand the behavior I'm seeing. This returns the location once, and then when I refresh the page it doesn't work again, it says TypeError: Cannot read property 'location' of undefined I have a feeling I'm not understanding how this all works.
All I'm trying to do is get access all the data returned from the API. If anyone has simple examples of doing it with TypeScript I'd really appreciate it. I can do this in normal JavaScript, but having trouble translating it over to TypeScript. My problem is similar to this post
const Webmap: FC = () => {
const url = 'https://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2019-10';
interface User {
id?: any;
location?: any;
}
const [users, setUserList] = useState<User[]>([]);
useEffect(() => {
axios.get<User[]>(url)
.then(response => {
// console.log(response.data);
setUserList(response.data);
});
}, [])
console.log(users[0].location)
What is users[0] before you populate the array with a call to setUserList? It's undefined. Maybe you should check that users[0] is non-nullish before you attempt to access its fields?
If it were me, I would not provide a default value to the useState call:
const [users, setUserList] = useState<User[]>();
which now means that the type of users will be User[] | undefined. Before the web request is made, the type of users will be undefined.
Now, when you want to use it, you can tell if it has been populated because checking that users is non-nullish
if(users != null){
// users is definitely populated from the web request
// although the array may contain no items
users.forEach(u => console.log(u));
}
...or... in JSX/TSX
{users && users.map(u => (<div>{u.location}</div>)}
will narrow the type of users from User[] | undefined to User[].
You still need to ensure that the indexes that you explicitly access after this point, (e.g. users[0]) actually exist before you try to reference their properties.
It is due to you trying to access the data even when it was not set in the state.
If users is not empty and truthy then log the data.
if(users && users.length > 0)){
console.log(users.location)
}
I am trying to write unit test using Jasmine ( in Typescript ) - for a class with a method that gets data placed on the window object.
class handler {
public getContext(key:string):string {
return home.getContext(key);
}
In the above method home is an object that is set the window object by an external mechanism.
The home object that is set is something like below
window.home = {
getContext: (key:string) => key,
getData: (key:string) => key,
}
And In my code, I just fetch this from the window object assign it to const home
const home = window.home;
Now, I am trying to write a test case for the getContext method of the handler class.
I tried setting up object on window in many ways but it is somehow always showing me the below error.
//arrange
(window as any).home = {
getContext: (Key:any) => Key,
getData: (key:any) => key,
};
const home = (window as any).home;
//act
const handler = new handler();
const context = handler.getContext('find');
//assert
expect(context ).toEqual('find');
But I am running into the below error.
Cannot read property 'getContext' of undefined.
It is not able to set/read home object that is set on the window. Could anyone explain the way I should be going to mock or come up with a good way of writing a test case for this.
Here is the implementation in TS Playground. Please set the window.home object first before running (instructions in the link below ).
https://www.typescriptlang.org/play#code/PTAECEFMDMHsCdKgJ6wK6nmgdqALgBZIAO8sA5vAIYC2ANKMQDaRUDOSsxkuqa8oAMaxsbWC1BVsAE0nTZhJHCZNYAdwCW2cvlj4ioTTPWhYAIwBWkQXlBb9SYaPGQAdKABQH4ACo--gMCg4JDQsKDQUB9gLxBIo2l1VwJYGiQAXlAAb1BySDwAYRE8SAAPPAAuUABrSGRQdIA+GrqGPLwAESo8Kira+qaW+oBfWPDxicmJqJiPUDiAQWgSgT45BQMUtNNLa1sRB0MtRLVQACUcfQ02TzmPJzZbLYzQAAoEk3ZJbGQASmTUpAANxeQRMdg3AhSaQsARZOaMNBmJgaQS5fJFbAlcqvfoVR7wLTkX74vCE7TZBGYfL8XDPVztTHYvC4uq-EGRSKjKmI5Go9GdbpUVnIUnk4liomUzky6l4WmgentLo9EXsnmjbkPJ7Q2EASVEPWwghe2EgpyhMlhr3VDxcrlU5FelphkHgBseUhNDIxxTKLIAREQVLAA79bSIxCwHRRnbq3R6jd7GX6cQG1AgmNIwxHnNHHXGrQnDV63Mqha8A-0cyCPEA
I'm trying to extract data from state. I'm using redux.
const {currentPost } = useSelector(state => state.posts)
I expected to get an object with properties. Instead I get couple of undefined and then I get an object.
These undefined on the start causes that I can't destructure further like const {currentPost: {id} } = useSelector(state => state.posts)and returns error that it can't read property of undefined.
These posts are obtained by API.
I've tried to workaround it by use a function which checks if this currentPost is undefined and then pass null into these properties. However it's not suitable for project and this solution is error prone.
As I get more experience I want to share my knowledge for future young frontend developers
I'm using redux-toolkit https://redux-toolkit.js.org/
These undefined values are from async operations, so its their behaviour that sometimes before promise is completed return undefined value.
To overcome it and write stable code there is a need to add default values. In redux-toolkit you can use
const slice = createSlice({
name: 'posts',
initialState: {
currentPosts: {
value: {
name: ''
}
},
posts: []
},
reducers: {
...reducers
},
})
In that case you'll get Object currentPosts, which is not undefined.
I'm using OpenWeatherAPI and React to make a weather app for practie, I'm able to retrieve my date data, but my temp data is giving some issues and I'm not totally sure why. Here is my error:
Uncaught TypeError: Cannot read property 'temp' of undefined
at Weather.js:31
Here is my Weather.js:
componentDidMount () {
axios.get('http://api.openweathermap.org/data/2.5/forecast?q=London,uk&appid=APIKEY')
.then(response => {
this.setState({forecasts: response.data.list});
});
}
render() {
const projections = this.state.forecasts.map(forecast => {
return <Subweather
date={forecast.dt_txt}
temp={forecast.main.temp}
key={forecast.id} /> ;
});
const weather = projections[0, 8, 16, 24, 32];
return (
<div className={classes.WeatherDiv}>
{weather}
</div>
Here is what the array looks like when I return it in the console (image attached).
I assumed that since I am mapping this to a new array, the best way to get this value is to use forecast.main.temp since the temp value is within the main but this obviously comes back as undefined so it's not there.
What am I missing here?
forecast is an array, so you need to access its elements. main is a property of each object belonging to this array. You may need to loop through each element to get all the data you need, but for retrieving the first entry you need to access the array element itself before main can be referenced:
var myTemp = forecast[0].main.temp;
Well the answer to your error is the asynchronous api call that you make in componentDidMount().
React doesn't guarantee to hold render() from being executed till the api call returns a response and hence your forecasts in state is undefined when render() is executed.
What I suggest is to rather set an initial default state for forecasts in your component so that it renders without any error. And once you receive the response in componentDidMount() your component will anyhow be re-rendered due to setState().
got the data in reducer but can't get in component.
this is my connection code.
const mapStateToProps =state => {
return {
name:state.fbLogin.name
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators(ActionCreators,dispatch);
}
export default connect(mapStateToProps,mapDispatchToProps)(Chat);
i want to access the name using this.props.name but got "undefined"
Check your store, make sure you have a reducer for fbLogin in place, the code seems to be correct, you may want to add default props so you don't get any undefined errors
restart your app ..
some time getting data from reducers give undefined after restarting the app
you can see the real data
hope this helps you