So I'm just practising my react redux skills. Im a beginner. I have created an action, reducer and several components. I'm basically making a todo app. I am fetching the data from an API which I have successfully done but the problem is arising when I'm trying to loop through the data and have it surrounded with <li> tags. I am getting Cannot read property 'map' of undefined which i dont understand why because in the console i can clearly see the array.
Action:
export function getLists(){
return function (dispatch) {
return fetch ("https://reqres.in/api/users?page=1")
.then( response => response.json())
.then (json => {console.log('sdsd'); console.log(json);
dispatch({ type: "ADD_ITEMS", payload: { json, loading: false} });
});
}
}
Reducer:
const initialState = {
todothings: [],
loading: true
};
function rootReducer (state = initialState, action) {
if( action.type === "ADD_ITEMS"){
console.dir("In the ADD_ITEMS reducer" + action.payload);
return Object.assign({}, state, {
todothings: state.todothings.concat(action.payload.json),
loading: action.payload.loading,
});
} else if ( action.type === "DELETE_ITEM") {
} else {
return state;
}
}
export default rootReducer;
ToDo Components:
import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';
class TodosComponent extends Component {
componentDidMount(){
console.log('in the Todos comp -> componentDidMount()');
this.props.getList();
}
render(){
const {todothings , loading} = this.props;
if(!loading){
return(
<div>
<p>dfd</p>
{console.log(todothings)}
<TodoItems list={todothings}></TodoItems>
</div>
)
} else {
return (
<p>Fetching from upstream.</p>
)
}
}
}
function mapStateToProps(state){
return {
todothings: state.todothings,
loading: state.loading,
}
}
function mapDispatchToProps(dispatch){
return {
getList: () => dispatch(getLists())
};
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;
TodoItem Component:
import React from 'react';
function TodoItems (props) {
return(
<div>
<ul>
{console.log('In the todoitems')}
{console.log(props)}
{props.list.map( element => (
<p>{element.data}</p>
))}
</ul>
</div>
);
}
export default TodoItems;
EDIT:
This is what I have so far now:
ToDoItems:
import React from 'react';
const TodoItems = ({ list = [] }) => {
if (list.length === 0) return null;
return (
<ul>
{list.map(item => (
<li key={item.id} {...item}>
<p>{item.first_name}</p>
</li>
))}
</ul>
);
};
export default TodoItems;
ToDo Component:
import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';
class TodosComponent extends Component {
componentDidMount(){
console.log('in the Todos comp -> componentDidMount()');
this.props.getList();
}
render(){
const {todothings , loading} = this.props;
if(!loading){
return(
<div>
<p>dfd</p>
{console.log('in the todo comp')}
{console.log(todothings)}
<TodoItems list={todothings.data}></TodoItems>
</div>
)
} else {
return (
<p>Fetching from upstream.</p>
)
}
}
}
function mapStateToProps(state){
return {
todothings: state.todothings,
loading: state.loading,
}
}
function mapDispatchToProps(dispatch){
return {
getList: () => dispatch(getLists())
};
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;
Reducer:
const initialState = {
todothings: [],
loading: true
};
function rootReducer (state = initialState, action) {
if( action.type === "ADD_ITEMS"){
console.dir("In the ADD_ITEMS reducer" + action.payload);
return Object.assign({}, state, {
todothings: state.todothings.concat(action.payload.json.data),
loading: action.payload.loading,
});
} else if ( action.type === "DELETE_ITEM") {
} else {
return state;
}
}
export default rootReducer;
Action:
export function getLists(){
return function (dispatch) {
return fetch ("https://reqres.in/api/users?page=1")
.then( response => response.json())
.then (json => {console.log('sdsd'); console.log(json);
dispatch({ type: "ADD_ITEMS", payload: { json, loading: false}
});
});
}
}
There are now no errors yet nothing is getting displayed:
(3) [{…}, {…}, {…}]
0: {id: 1, email: "george.bluth#reqres.in", first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}
1: {id: 2, email: "janet.weaver#reqres.in", first_name: "Janet", last_name: "Weaver", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"}
2: {id: 3, email: "emma.wong#reqres.in", first_name: "Emma", last_name: "Wong", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
length: 3
__proto__: Array(0)
Afternoon,
I think the data you want is from prop.list.data not props.list within <TodoItems />
In your component <TodDo /> try:
<TodoItems list={todothings.data}></TodoItems>
Then tidy up your stateless component <TodoItems /> (to cover an empty array):
const TodoItems = ({ list = [] }) => {
if (list.length === 0) return null;
return (
<ul>
{list.map(item => (
<li key={item.id} {...item}>
<ul>
{Object.keys(item).map((data, key) => (
<li {...{ key }}>{data}</li>
))}
</ul>
</li>
))}
</ul>
);
};
Note:
Your array has an object, with this shape:
{
id: 1,
email: "g.buth#reqres.in",
first_name: "George",
last_name: "Bluth"
}
What do you want to return in your <li>?
Update to loop through object.
Related
I am making a react-redux site.
I am accessing data called from an api via redux.
I understand that ComponentDidMount will not wait for this data to be called so I was wondering on a better way to split this data within a parent component into arrays for children components (or if this method is a bad choice).
This is the component and will hopefully shed some light on what is going on.
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { fetchPosts, fetchItins } from "../../../actions/postActions";
import TravelAlerts from "./TravelAlerts//travelAlert";
import IntelligenceAlerts from "./IntelligenceAlerts/IntelligenceAlert";
import AllAlerts from "./AllAlerts/AllAlerts";
class Alerts extends Component {
state = {
showAllAlerts: true,
showAllIntelligenceAlerts: false,
showAllTravellers: false,
currentPage: 1,
alertsPerPage: 20,
travelAlerts: [],
intelligenceAlerts: [],
};
componentDidMount() {
this.props.fetchPosts();
console.log(this.props.posts);
for (var key in this.props.posts) {
if (this.props.posts.hasOwnProperty(key)) {
if (key === "travelAlerts") {
alert("travel ALerts Hit");
} else if (key === "intelligenceAlerts") {
alert("intelligenceAlertsHIts");
} else {
}
console.log(key + " -> " + this.props.posts[key]);
}
}
}
//navigation helper
DisableAlerts() {
this.setState({
showAllAlerts: false,
showAllIntelligenceAlerts: false,
showAllTravellers: false,
});
}
//pagination change page
handleClick(number) {
this.setState({
currentPage: number,
});
}
ToogleAlertType(name) {
this.DisableAlerts();
if (name === "All") {
this.setState({ showAllAlerts: true });
} else if (name === "Intelligence") {
this.setState({ showAllIntelligenceAlerts: true });
} else if (name === "Travellers") {
this.setState({ showAllTravellers: true });
} else {
this.setState({ showAllAlerts: true });
}
}
render() {
return (
<div>
<button
style={{ width: "30%" }}
onClick={() => this.ToogleAlertType("ALL")}
>
ALL{" "}
</button>
<button
style={{ width: "30%" }}
onClick={() => this.ToogleAlertType("Intelligence")}
>
Intelligence{" "}
</button>
<button
style={{ width: "30%" }}
onClick={() => this.ToogleAlertType("Travellers")}
>
Travellers
</button>
<br />
<hr />
<div>
{this.state.showAllAlerts ? (
<>{/* <AllAlerts alerts={this.props.posts} /> */}</>
) : (
<></>
)}
</div>
<>
{this.state.showAllTravellers ? (
<>
<></>
{/* <TravelAlerts alerts={this.props.posts} /> */}
</>
) : (
<></>
)}
</>
<>
{this.state.showAllIntelligenceAlerts ? (
<>{/* <IntelligenceAlerts alerts ={this.props.posts}/> */}</>
) : (
<></>
)}
</>
</div>
);
}
}
Alerts.propTypes = {
fetchPosts: PropTypes.func.isRequired,
posts: PropTypes.object.isRequired,
// newPost: PropTypes.object
};
const mapStateToProps = (state) => ({
posts: state.posts.items,
// newPost: state.posts.item
});
export default connect(mapStateToProps, { fetchPosts })(Alerts);
The component is mapped to redux and is working fine however the data being retrieved is within an object and I would like this to be two separate arrays which I could then pass down to the child components etc.
This is what I am currently trying to do in the component did mount just to see if it can find the keys.
componentDidMount() {
this.props.fetchPosts();
console.log(this.props.posts);
for (var key in this.props.posts) {
if (this.props.posts.hasOwnProperty(key)) {
if (key === "travelAlerts") {
alert("travel ALerts Hit");
} else if (key === "intelligenceAlerts") {
alert("intelligenceAlertsHIts");
} else {
}
console.log(key + " -> " + this.props.posts[key]);
}
}
}
However the data does not show when mounted(works in render method but I feel that is not a good place to put it).
Is this a good direction to head in or should I have split these into two separate arrays before they have even reached the component? If so should this be done so in the reducer or in the actions?
Really appreciate any help as I am new to redux.
EDIT
This is my fetch posts
export const fetchPosts = () => (dispatch) => {
fetch(
"the url im using"
)
.then((res) => res.json())
.then((posts) =>
dispatch({
type: FETCH_POSTS,
payload: posts,
})
);
};
My reducer
import { FETCH_POSTS, NEW_POST, FETCH_ITINS } from "../actions/types";
const initialState = {
items: {},
item: {},
itins: [],
};
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_POSTS:
return {
...state,
items: action.payload,
};
case NEW_POST:
return {
...state,
item: action.payload,
};
case FETCH_ITINS:
return {
...state,
itins: action.payload,
};
default:
return state;
}
}
This is just a sample code I am trying to control my controlled inputs using Redux, I add the Redux to my React project and add my reducer and action but everything works well except updating my component in one of my actions.
the following code is my Reducer:
import actionTypes from "./actions";
const uniqid = require("uniqid");
const firstID = uniqid();
const initialState = {
cons: [
{
value: "",
id: firstID,
added: false
}
],
pros: [
{
value: "",
id: firstID,
added: false
}
],
num: 0
};
const reducer = (state = initialState, action) => {
const newState = { ...state };
switch (action.type) {
case actionTypes.HANDLEINPUTCHANGE:
// const newState = state;
const changingItem = newState[action.case].find(item => {
return item.id === action.id;
});
const changingItemIndex = newState[action.case].findIndex(item => {
return item.id === action.id;
});
changingItem.value = action.event;
if (
changingItemIndex === newState[action.case].length - 1 &&
!changingItem.added
) {
alert(123);
const newItem = {
id: uniqid(),
value: "",
added: false
};
newState[action.case].push(newItem);
changingItem.added = true;
console.log(newState);
}
newState[action.case][changingItemIndex] = changingItem;
return newState;
case actionTypes.CLICK:
newState.num += 1;
return {
...newState
};
default:
return state;
}
};
export default reducer;
and the following code is my component, unfortunately, the HANDLEINPUTCHANGE action type did not update my component:
import React, { Component } from "react";
import FormElement from "../../base/components/formElement/FormElement";
import actionTypes from "../../base/store/actions";
import { connect } from "react-redux";
import "./style.scss";
class FormGenerator extends Component {
render() {
console.log(this.props);
return (
<ul className="row formGeneratorContainer fdiColumn">
<li onClick={this.props.click}>{this.props.num}</li>
{this.props[this.props.case].map((item, index) => {
return (
<li className="row formGeneratorItem" key={index}>
<div className="bullet d_flex jcCenter aiCenter">1</div>
{/* <FormElement onChange={(e,index,type,)}/> */}
<input
name={item.id}
type="text"
onChange={event =>
this.props.onFieldValueChange(
event.target.value,
index,
this.props.case,
item.id
)
}
/>
</li>
);
})}
</ul>
);
}
}
const mapStateToProps = state => {
return {
cons: state.cons,
pros: state.pros,
num: state.num
};
};
const mapDispachToProps = dispatch => {
return {
onFieldValueChange: (event, index, c, id) =>
dispatch({
event: event,
index: index,
case: c,
id: id,
type: actionTypes.HANDLEINPUTCHANGE
}),
click: () => dispatch({ type: actionTypes.CLICK })
};
};
export default connect(
mapStateToProps,
mapDispachToProps
)(FormGenerator);
You need to set value of your controlled component:
<input
name={item.id}
type="text"
value={item.value}
onChange={event =>
this.props.onFieldValueChange(
event.target.value,
index,
this.props.case,
item.id
)
}
/>
Other problems are in your reducer, you are mutating the redux state with these lines:
newState[action.case].push(newItem);
// ...
newState[action.case][changingItemIndex] = changingItem;
Look at these sections in the redux documentation:
Inserting and Removing Items in Arrays
Updating an Item in an Array
I am new to to redux and react. Still doing simple tutorials. I managed to create 2 simple components; one that outputs on the screen (as a list) whatever is in the array in the redux store, and the other component contains a button and a textfield which basically adds to that array in the store.
I would like to add a feature that will enable me to delete a specific entry in the list depending on what the user clicked on. I am thinking of creating a <button> next to each <li> tag that gets rendered as it loops through the array, and these buttons will correspond to the respective list elements. But I'm not sure how to do that.
I've tried creating a button when each <li> tag gets created but I was getting an error on the console stating that each element in a list needs a unique ID. I then decided to create another array in my store called buttons which will contain a unique id as well as the id of the list but it got out of hand. I think I might be overcomplicating this. This is what I have at the moment:
Components:
List.jsx (responsible for outputting the list)
import React from 'react'
import { connect } from "react-redux";
const ListComp = ({ lists }) => (
<div>
<ul>
{console.log(lists)}
{lists.map( element => (
<li key={element.id}>
{element.titleToBeAddedToList}
</li>
))}
</ul>
</div>
)
const mapStateToProps = state => {
return {
lists: state.lists
};
}
const List = connect(mapStateToProps)(ListComp)
export default List;
SubmitButton.jsx (responsible for outputting the button and textfield)
import React from 'react'
import { connect } from "react-redux";
import uuidv1 from "uuid";
import { addList } from "../actions/index";
import { addButton } from "../actions/index"
function mapDispatchToProps(dispatch){
return {
addlist: article => dispatch(addList(article)),
addbutton: idOfButton => dispatch(addButton(idOfButton))
};
}
class Submit extends React.Component{
constructor(){
super();
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.id]: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
const {titleToBeAddedToList} = this.state;
const id = uuidv1();
const button_id = uuidv1();
//Dispatching the action:
this.props.addlist({ titleToBeAddedToList, id });
this.props.addbutton({id, button_id});
//Once we've dispatched an action, we want to clear the state:
this.setState({ titleToBeAddedToList: "" });
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="titleToBeAddedToList"
onChange={this.handleChange}
/>
</div>
<button type="submit" className="btn btn-success btn-lg">
SAVE
</button>
</form>
);
}
}
const SubmitButton = connect(null, mapDispatchToProps)(Submit)
export default SubmitButton;
Reducers:
const initialState = {
lists: [],
buttons: []
};
function rootReducer (state = initialState, action) {
if(action.type === "ADD_LIST" ){
return Object.assign({}, state, {
lists: state.lists.concat(action.payload)
});
} else if(action.type === "ADD_BUTTON"){
return Object.assign({}, state, {
buttons: state.lists.concat(action.payload)
});
} else if(action.type === "DELETE_FROM_LIST"){
//.....//
}
return state;
}
export default rootReducer;
Action:
export function addList(payload) {
return { type: "ADD_LIST", payload }
};
export function addButton(payload){
return {type: "ADD_BUTTON", payload }
}
export function deleteList(payload){
return { type: "DELETE_FROM_LIST", payload }
}
Store:
import { createStore } from "redux";
import rootReducer from "../reducers/index";
const store = createStore(rootReducer);
export default store;
You can use Math.random() as an unique key identifier, if the button is click it will call action deleteItem with the ID, action is bound to reducer pass on the ID, you can then use the ID to indentify elements and remove it in the list.
import React from 'react'
import { connect } from "react-redux";
import { deleteItem } from './actions';
const ListComp = ({ lists }) => (
<div>
<ul>
{console.log(lists)}
{lists.map( element => (
<li key={Math.random()} key={element.id}>
{element.titleToBeAddedToList}
<button onClick={() => deleteItem(element.id)}>X</button>
</li>
))}
</ul>
</div>
)
const mapStateToProps = state => {
return {
lists: state.lists
};
}
const List = connect(mapStateToProps, {deleteItem})(ListComp) // Make it available to component as props
export default List;
Action:
export function deleteElement(id) {
return function(dispatch) {
return dispatch({type: "DELETE_FROM_LIST", payload: id})
}
}
Reducer:
case 'DELETE_FROM_LIST': {
const id = action.payload;
return {
...state,
list: state.list.filter(item => item.id !== id)
}
}
else if (action.type === "DELETE_FROM_LIST") {
return Object.assign({}, state, {
buttons: state.lists.filter(item => (item.id !==action.payload))
});
}
you can use filter() for delete.
This is a minimal working react-redux example containing all the pieces to delete an item from an array in redux store.
// reducer.js
const reducer = (state, action) => {
switch (action.type) {
case 'DELETE':
return state.filter(item => (
item.id !== action.payload.id
))
default: return state;
}
}
// Item.js
const Item = ({id, onClick, label}) => (
<li>
{label}
<button onClick={ () => onClick(id) }>
delete
</button>
</li>
)
// ListContainer.js
const mapStateToProps = state => ({ items: state })
const ListContainer = ReactRedux.connect(mapStateToProps)(class extends React.Component {
handleDelete = id => {
const { dispatch } = this.props;
dispatch({ type: 'DELETE', payload: { id } })
}
render() {
const { items } = this.props;
return items.map(({id, label}) => (
<Item
label={label}
id={id}
onClick={this.handleDelete}
/>
))
}
})
// Main.js
const initialState = [
{ id: 1, label: 'item 1' },
{ id: 2, label: 'item 2' },
{ id: 3, label: 'item 3' },
{ id: 4, label: 'item 4' }
]
const store = Redux.createStore(reducer, initialState);
class App extends React.Component {
render(){
return (
<ReactRedux.Provider store={store}>
<ListContainer />
</ReactRedux.Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/6.0.1/react-redux.js"></script>
<div id="root"></div>
I have created an UPDATE_ITEM type but how to code it in here I don't have the idea since I want to update it by its ID. Also I want to dipatch this action with the reducer itemReducer.js which I have given in the code below. Can someone please help me with the code?//itemAction.js Action. The get, delete and add routes is working but this put method is giving me headache.
import axios from 'axios';
import { GET_ITEMS, ADD_ITEM, DELETE_ITEM, UPDATE_ITEM, ITEMS_LOADING } from'./types';
export const getItems = () => dispatch => {
dispatch(setItemsLoading());
axios.get('/api/items').then(res =>
dispatch({
type: GET_ITEMS,
payload: res.data
})
);
};
export const addItem = item => dispatch => {
axios.post('/api/items', item).then(res =>
dispatch({
payload: res.data
})
);
};
//UPDATE_ITEM Action Here
export const deleteItem = id => dispatch => {
axios.delete(`/api/items/${id}`).then(res =>
dispatch({
type: DELETE_ITEM,
payload: id
})
);
};
export const setItemsLoading = () => {
return {
type: ITEMS_LOADING
};
};
This is the itemReducer which I also need help
import { GET_ITEMS, DELETE_ITEM, UPDATE_ITEM, ADD_ITEM, ITEMS_LOADING
} from '../actions/types';
const initialState = {
items: [],
loading: false
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_ITEMS:
return {
...state,
items: action.payload,
loading: false
};
case DELETE_ITEM:
return {
...state,
items: state.items.filter(item => item._id !== action.payload)
};
//UPDATE_ITEM Reducer here
case ADD_ITEM:
return {
...state,
items: [action.payload, ...state.items]
};
case ITEMS_LOADING:
return {
...state,
loading: true
};
default:
return state;
}
}
I guess your update looks like the add:
//UPDATE_ITEM Action
export const updateItem = item => dispatch => {
axios.put('/api/items', item).then(res =>
dispatch({
type:'UPDATE_ITEM',
payload: res.data
})
);
};
In your reducer you can use map
case UPDATE_ITEM:
return {
...state,
items: state.items.map(
item =>
item._id === action.payload.id
//return action payload (modified item) instead of
// original item when item id is updated item id
? action.payload
: item//ids not the same, return original item
)
};
import React, { Component } from 'react';
import { Container, ListGroup, ListGroupItem, Button } from 'reactstrap';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { connect } from 'react-redux';
import { getItems, deleteItem, updateItem } from '../actions/itemActions';
import PropTypes from 'prop-types';
class ShoppingList extends Component {
componentDidMount() {
this.props.getItems();
}
onDeleteClick = id => {
this.props.deleteItem(id);
};
render() {
const { items } = this.props.item;
return (
<Container>
<ListGroup>
<TransitionGroup className="shopping-list">
{items.map(({ _id, name, body }) => (
<CSSTransition key={_id} timeout={500} classNames="fade">
<ListGroupItem>
<Button
className="remove-btn"
color="danger"
size="sm"
onClick={this.onDeleteClick.bind(this, _id)}
>
DELETE
</Button>
{/*An update button will be called here*/}
{/*<Button
className="update-btn"
color="success"
size="sm"
>
Update
</Button>*/}
<div></div>
<table className="rows">
<thead>
<tr>
<td>Name</td>
<td>Body</td>
</tr>
</thead>
<tbody>
<tr>
<td>{ name }</td>
<td>{ body }</td>
</tr>
</tbody>
</table>
</ListGroupItem>
</CSSTransition>
))}
</TransitionGroup>
</ListGroup>
</Container>
);
}
}
ShoppingList.propTypes = {
getItems: PropTypes.func.isRequired,
item: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
item: state.item
});
export default connect(
mapStateToProps,
{ getItems, deleteItem }
)(ShoppingList);
How can I fetch only one data and write it to Header ?
I am using firebase and react-redux.
firebase structure i try to write "organization": inovanka:
Action File Codes:
import firebase from 'firebase';
import { Actions } from 'react-native-router-flux';
import { ORGANIZATION_NAME_DATA_SUCCESS } from './types';
export const organizationName = () => {
const { currentUser } = firebase.auth();
return (dispatch) => {
firebase.database().ref(`/organizations/${currentUser.uid}`)
.on('value', snapshot => {
dispatch({ type: ORGANIZATION_NAME_DATA_SUCCESS, payload: snapshot.val() });
});
};
}
Reducer File :
import { ORGANIZATION_NAME_DATA_SUCCESS } from '../actions/types';
const INITIAL_STATE = {
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case ORGANIZATION_NAME_DATA_SUCCESS:
console.log(action); // data retrieved as array
return action.payload
default:
return state;
}
};
Component: (I would like to write it to this)
class HomePage extends Component {
componentWillMount() {
}
render() {
return (
<Container>
<Header>
<Text> i would like to write it here </Text>
</Header>
<Content>
</Content>
</Container>
);
}
}
const mapStateToProps = ({ homepageResponse }) => {
const organizationArray = _.map(homepageResponse, (val, uid) => {
return { ...val, uid }; //
});
return { organizationArray };
};
export default connect(mapStateToProps, { organizationName })(HomePage);
Change this:
firebase.database().ref(`/organizations/${currentUser.uid}`)
.on('value', snapshot => {
to this:
firebase.database().ref(`/organizations/${currentUser.uid}`)
.once('value', snapshot => {
using once() will read data only one time, thus fetching only one data
Solution is Here !
Action File:
export const organizationName = () => {
const { currentUser } = firebase.auth();
return (dispatch) => {
firebase.database().ref(`/organizations/${currentUser.uid}`)
.once('value', snapshot => {
_.mapValues(snapshot.val(), o => {
console.log(o);
dispatch({ type: ORGANIZATION_NAME_DATA_SUCCESS, payload: {organization: o.organization, fullname: o.fullname }});
});
});
};
}
Reducer File
const INITIAL_STATE = {
organization: '',
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case ORGANIZATION_NAME_DATA_SUCCESS:
console.log(action);
return {...state, organization:action.payload.organization };
default:
return state;
}
};
Component File MapToStateProps and componentWillMount
const mapStateToProps = state => {
const { organization, fullname } = state.homepageResponse;
console.log("burada" + organization);
return { organization, fullname };
};
componentWillMount(){
this.props.organizationName();
}
*Last Step Header *
render() {
return (
<Container>
<Header>
<Text> { this.props.organization } </Text>
</Header>
</Container>
}
Thank You Everyone