Reputation: 229
I have a component that's state I'm trying to use in other components, it has to be used in multiple components so i'm switching it to redux. Right now using the same function that works in my component, I am getting the error 'newUsers.push is not a function'
Below is my redux action:
import { FETCH_USERS_TO_ADD } from './types';
import axios from 'axios'
export const fetchUsersToAdd = () => dispatch => {
var userBox = [];
var newUserBox = [];
let newUserIds = {};
let newUsers = [];
axios.all([
axios.get('/updateUserList'),
axios.get('/userInformation')
])
.then(axios.spread((newUsers, currentUsers) => {
userBox.push(newUsers.data)
newUserBox.push(currentUsers.data)
for (let newUser of newUserBox){
newUserIds[newUser.id] = newUser.id
}
for (let user of userBox){
if(!newUserIds[user.staffID]){
console.log(user)
**newUsers.push(user)**
}
}
})).then(dispatch({
type: FETCH_USERS_TO_ADD,
payload: newUsers
}))
}
The Code Below in My class component doesnt give me this error: let newUserIds = {}; let newUsers = [];
this.state = {
userBox : [],
newUserBox : [],
usersToBeAdded:[],
}
componentDidMount(){
axios.all([
axios.get('/updateUserList'),
axios.get('/userInformation')
])
.then(axios.spread((newUsers, currentUsers) => {
this.setState({
userBox : newUsers.data,
newUserBox : currentUsers.data,
})
}))
}
checkForNewUsers = (e) => {
for (let newUser of this.state.newUserBox){
newUserIds[newUser.id] = newUser.id
}
for (let user of this.state.userBox){
if(!newUserIds[user.staffID]){
newUsers.push(user)
}
}
this.setState({
usersToBeAdded:newUsers
})
console.log(newUsers)
}
<UpdateUsersButton onClick={this.checkForNewUsers}/>
When user is consoled it returns an array like this:
Array(10)
0: {staffID: 1, dept: "Junior Web Developer", email: "[email protected]", name: "manasa", password: "$2y$10$/zYS7OhzwdLOi6Slzc3xxxxxiY0y1J6MjnLCN24GmZ3rMHWUS"}
1: {staffID: 2, dept: "Web Developer", email: "[email protected]", name: "Julio Fajardo", password: "$2y$10$MphAC8aRY2uzs1Zxxxxxnd7t0KukEkvGbx5Y4van.Da6"}
Upvotes: 1
Views: 454
Reputation: 26878
I think it's because newUsers
gets shadowed in the arrow function and isn't what you think it is anymore. Don't reuse variable names.
Try this:
import { FETCH_USERS_TO_ADD } from './types';
import axios from 'axios'
export const fetchUsersToAdd = () => dispatch => {
var userBox = [];
var newUserBox = [];
let newUserIds = {};
let newUsersArr = []; // Make unique
axios.all([
axios.get('/updateUserList'),
axios.get('/userInformation')
])
.then(axios.spread((newUsers, currentUsers) => { // Was shadowed here
userBox.push(newUsers.data)
newUserBox.push(currentUsers.data)
for (let newUser of newUserBox){
newUserIds[newUser.id] = newUser.id
}
for (let user of userBox){
if(!newUserIds[user.staffID]){
console.log(user)
newUsersArr.push(user)
}
}
})).then(dispatch({
type: FETCH_USERS_TO_ADD,
payload: newUsersArr
}))
}
Upvotes: 2