Warning: unstable_flushDiscreteUpdates when rendering component in React - javascript

I've been trying to render a component using map, the render happens but with a warning:
Warning: unstable_flushDiscreteUpdates: Cannot flush updates when
React is already rendering.
MyBooks.js
import React, { useState, useEffect } from 'react';
import ActionAreaCard from '../components/ActionAreaCard';
const MyBooks = ({address}) => {
const [metadata, setMetadata] = useState([]);
const URL = `http://localhost:3001/api/tatumapi`;
const chain = 'CELO';
const params = { address: address, chain: chain };
useEffect(() => {
fetch(URL,
{
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(response => response.json())
.then(data => setMetadata(
(data.data).map((data2) => {
return data2.metadata.map((data3) => {
return data3;
})
})
))
}, [])
return (
<div>
{metadata.map((data4) => {
return (
<div>
{data4.map(({metadata}) => {
return (
<div>
{metadata!= null && console.log(metadata)}
{metadata!=null && <ActionAreaCard name={metadata.name} description={metadata.description} image={metadata.image}/>}
</div>
)
})}
</div>
)
})}
</div>
)
}
export default MyBooks;
Console output:
{description: 'The very first edition', name: 'BOOK', image: 'ipfs://bafkreidny67q3xxjulstouk7vzp6bomdbnokg3zzhg6k4gqbdtutqzz5h4'}
description: "The very first edition"
image: "ipfs://bafkreidny67q3xxjulstouk7vzp6bomdbnokg3zzhg6k4gqbdtutqzz5h4"
name: "BOOK"
[[Prototype]]: Object
Why I'm getting this warning and how can I solved it?

I've just improved the mapping and added a key.
import React, { useState, useEffect } from 'react';
import ActionAreaCard from '../components/ActionAreaCard';
const MyBooks = ({address}) => {
const [metadata, setMetadata] = useState([]);
const URL = `http://localhost:3001/api/tatumapi`;
const chain = 'CELO';
const params = { address: address, chain: chain };
useEffect(() => {
fetch(URL,
{
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(response => response.json())
.then(data => setMetadata(data.data.map(data2 => {
return data2;
})))
}, [])
return(
<div>
{metadata!=undefined && metadata!=null && metadata.map((data) => {
return data.metadata.map(({metadata}, i) => {
return (
<div key={i}>
{metadata!==null && <ActionAreaCard name={metadata.name} description={metadata.description} image={metadata.image}/>}
</div>
)
})
})}
</div>
)
}
export default MyBooks;

Related

TypeError: Cannot read properties of undefined (reading 'url')

I'm working on building a drag and drop card game. I'm not familiar with using the library react-dnd I wonder if this has something to do with it. If I use data already on the file, it works fine, but if I have to fetch the data, it creates This error.
As I said, this usually happens when I use useEffect Somebody has a better idea of how to do this, please let me know.
import React, { useEffect, useState } from 'react';
import Card from './Card';
import { useDrop } from 'react-dnd';
import './Table.css';
const API_Data = [
{
id: 1,
url: 'https://deckofcardsapi.com/static/img/6H.png',
},
{
id: 2,
url: 'https://deckofcardsapi.com/static/img/aceDiamonds.png',
},
{
id: 3,
url: 'https://deckofcardsapi.com/static/img/7C.png',
},
{
id: 4,
url: 'https://deckofcardsapi.com/static/img/6H.png',
},
{
id: 5,
url: 'https://deckofcardsapi.com/static/img/aceDiamonds.png',
},
{
id: 6,
url: 'https://deckofcardsapi.com/static/img/7C.png',
},
];
function Table() {
const [playersCard, setPlayersCard] = useState([]);
const [potA, setPotA] = useState([
{
id: 1,
url: 'https://deckofcardsapi.com/static/img/6H.png',
},
]);
const [potB, setPotB] = useState([]);
/////////////////////////////////////////////////////////////////////////
const [, dropA] = useDrop(() => ({
accept: 'card',
drop: (item) => handleAddToPotA(item.id),
collect: (monitor) => ({
isOver: !!monitor.isOver(),
}),
}));
const handleAddToPotA = (id) => {
const newCard = playersCard.filter((card) => id === card.id);
console.log(`newCard`, newCard);
setPotA((oldCard) => [...oldCard, newCard[0]]);
};
//////////////////////////////////////////////////////////////////////////
const [, dropB] = useDrop(() => ({
accept: 'card',
drop: (item) => handleAddToPotB(item.id),
collect: (monitor) => ({
isOver: !!monitor.isOver(),
}),
}));
const handleAddToPotB = (id) => {
const newCard = playersCard.filter((card) => id === card.id);
setPotB((oldCard) => [...oldCard, newCard[0]]);
console.log(newCard);
};
useEffect(() => {
setPlayersCard(API_Data);
return () => {};
}, []);
//////////////////////////////////////////////////////////////////////////
if (!playersCard) {
return <div></div>;
}
return (
<div className="table-page">
<div className="center-table">
<div className="pot-a" ref={dropA}>
{potA &&
potA.map((card) => {
return <Card url={card?.url} id={card.id} key={card.id} />;
})}
</div>
<div className="pot-b" ref={dropB}>
{potB &&
potB.map((card) => {
return <Card url={card.url} id={card.id} key={card.id} />;
})}
</div>
</div>
<div className="players-card">
{playersCard.map((card) => {
return <Card url={card.url} id={card.id} key={card.id} />;
})}
</div>
</div>
);
}
export default Table;
Because playersCard is not initialized yet.
try to check undefined first
<div className="players-card">
{playersCard.length > 0 && playersCard.map((card) => {
return <Card url={card.url} id={card.id} key={card.id} />;
})}
</div>
A Possible Reason:
Check your function and method names for typos

Loop data every 20 seconds instead of showing all

I'm trying to figure out the best way to loop through this data, right now I'm getting all 'Job Names' that are the id of 6 from my API. What I'd like to do is only show one at a time for 20 seconds or so, then move to the next only showing one at a time but continuously looping through all.
Any suggestions?
Here is one api call getting the titles of Job Names:
import { React, Component } from 'react';
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXX_XXXXX_XXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
class Title extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"where": "{40.CT. 'In Progress'}","sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => response.json())
.then( data => this.setState({ data })
);
}
render() {
const { data } = this.state;
if (data === null) return 'Loading Job Data... ';
return (
<div className="Title">
{Object.keys(data["data"]).map(item => (
<div key = {item}>
<h2>
{data["data"][item][6].value}
</h2>
</div>
))}
</div>
)
}
}
export default Title;
UPDATE: So after some researching I'm seeing some ideas on what I'm looking to do. like so:
let data = ['Job Name 1',
'Job Name 2',
'Job Name 3',
'Job Name 4',
'Job Name 5',
'Job Name 6',
'Job Name 7',
'Job Name 8',
'Job Name 9',
'Job Name 10'];
let interval = 2000; //I'll set to twenty seconds in production...
data.forEach((data, index) => {
setTimeout(() => {
console.log(data)
}, index * interval)
})
Similar to this, but Set this to loop continuously, so after 10, go back to 1. Is this where I'd use setInterval() instead of setTimeout()?
Once I get this set in accurately, I'd like to set LineCharts up that will populate based on what Title(Job Name) is displaying, changing when the Title does automatically...
UPDATE wanted to update to show How i've set the cycle in for my Job Names in my App.js, and sending this as a prop to my Title.js:
App.js
import React, { useEffect, useState } from "react";
import './App.css'
import Title from './components/header/Title'
import TotalLineChart from './components/charts/TotalLineChart'
import RadiantLineChart from './components/charts/RadiantLineChart'
import PlumbingLineChart from './components/charts/PlumbingLineChart'
import SnowmeltLineChart from './components/charts/SnowmeltLineChart'
import HVACLineChart from './components/charts/HVACLineChart'
import GasPipeLineChart from './components/charts/GasPipeLineChart'
import FixturesLineChart from './components/charts/FixturesLineChart'
// import TitleCycle from './components/TitleCycle'
// import Logo from './components/Logo';
let headers = {
"QB-Realm-Hostname": "XXXXXXXXX.quickbase.com",
"User-Agent": "FileService_Integration_V2.1",
"Authorization": "QB-USER-TOKEN XXXXXXXXX",
"Content-Type": "application/json",
"Retry-After": 120000
};
function App() {
const [allData, setAllData] = useState([]);
const [index, setIndex] = useState(0);
// Fetch all data, all jobs
useEffect(() => {
function fetchData() {
let body = {
from: "bpz99ram7",
select: [3, 6, 40],
where: "{40.CT. 'In Progress'}",
sortBy: [{ fieldId: 6, order: "ASC" }],
groupBy: [{ fieldId: 40, grouping: "equal-values" }],
options: { skip: 0, top: 0, compareWithAppLocalTime: false },
};
fetch("https://api.quickbase.com/v1/records/query", {
method: "POST",
headers: headers,
body: JSON.stringify(body),
})
.then((response) => response.json())
.then(({ data }) => setAllData(data));
}
fetchData();
}, []);
// Cycle through the jobIds and indexes
useEffect(() => {
const timerId = setInterval(
() => setIndex((i) => (i + 1) % allData.length),
5000 // 5 seconds.
);
return () => clearInterval(timerId);
}, [allData]);
// console.log(allData)
// console.log(index)
// Calculate info based on index
const jobId = allData[index]?.['3']?.value || '291'; // Default 291
const title = allData[index]?.['6']?.value || 'Default Title';
// console.log(jobId)
return (
<div>
{/* <div className="flexbox-container">
<div className="Logo">
{/* <Logo /> */}
{/* </div> */}
<div className="App">
<Title title = {title} />
</div>
<div className="TopChart">
<TotalLineChart jobId = {jobId} />
</div>
<div className="FirstRowContainer">
{/* <RadiantLineChart jobId = {jobId} /> */}
<PlumbingLineChart jobId = {jobId} />
<FixturesLineChart jobId = {jobId} />
</div>
<div className="SecondRowContainer">
<SnowmeltLineChart jobId = {jobId} />
<HVACLineChart jobId = {jobId} />
<GasPipeLineChart jobId = {jobId} />
</div>
</div>
);
}
export default App;
Title.js
import React from 'react'
function Title(props) {
const { title } = props;
return (
<div>
{ title }
</div>
)
}
export default Title
This allows the cycle and show one at a time based on the duration set in App.js.
I am not sure how your data looks like, but below is my closest guess.
import { React, Component } from 'react';
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXX_XXXXX_XXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
class Title extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
displayItem : ''
};
this.dataInterval;
}
componentDidMount() {
this.fetchData();
}
startShowingData(data) {
let counter = 0;
let dataKeys = Object.keys(data["data"])
this.dataInterval = setInterval(() => {
this.setState({...this.state, displayItem: data[dataKeys[counter]]});
counter++; // you have to reset this counter at your wish or you have to do clearInterval(this.dataInterval) after array is completely traversed.
}, 20000)
}
fetchData = () => {
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"where": "{40.CT. 'In Progress'}","sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => response.json())
.then( data => this.startShowingData(data.data));
}
render() {
const { data } = this.state;
if (data === null) return 'Loading Job Data... ';
return (
<div className="Title">
<h2>
{this.state.displayItem}
</h2>
</div>
)
}
}
export default Title;

How to filter props in Next.js? Can't filter data in props from componentDidMount in Next.js

I get data into the props of my component by using getStaticProps. I then want to filter that data before I use it in the component. Usually I'd do this in componentDidMount, but that's not possible as it seems like the props are populated after componentDidMount is called.
What's the best practice for working around this?
Here's my current code:
class Definition extends Component {
constructor({ router }, ...props) {
super(props);
this.state = {
songsArray: [],
};
}
filterSpotifyResults = () => {
const filteredArray = [];
this.props.songsData.tracks.items.forEach((obj) => {
if (obj.explicit === true) {
return;
} else {
filteredArray.push(obj);
}
});
this.setState({ songsArray: filteredArray });
};
componentDidMount = () => {
this.filterSpotifyResults();
};
render() {
if (this.props.router.isFallback) {
return <h4>Loading...</h4>;
}
return (
<div>
<h3>this is where the definition will go</h3>
<ul>
{this.props.wordsData.definitions.map((obj, i) => (
<li key={i}>{obj.definition}</li>
))}
</ul>
<iframe
src={`https://open.spotify.com/embed/track/${this.props.songsData.tracks.items[0].id}`}
width="300"
height="380"
allowtransparency="true"
allow="encrypted-media"
></iframe>
</div>
);
}
}
export default withRouter(Definition);
export async function getStaticProps(context) {
const wordsRes = await fetch(
`https://wordsapiv1.p.rapidapi.com/words/${context.params.word}/definitions`,
{
method: "GET",
headers: {
"x-rapidapi-key": process.env.NEXT_PUBLIC_DB_KEY,
"x-rapidapi-host": "wordsapiv1.p.rapidapi.com",
},
}
)
.then((response) => {
return response;
})
.catch((err) => {
console.error(err);
});
const songsRes = await fetch(
`https://api.spotify.com/v1/search?q=${context.params.word}&type=track`,
{
method: "GET",
headers: {
authorization:
"Bearer " + process.env.NEXT_PUBLIC_ENV_SPOTIFY_ACCESS_TOKEN,
},
}
)
.then((response) => {
return response;
})
.catch((err) => {
console.error(err);
});
const wordsData = await wordsRes.json();
const songsData = await songsRes.json();
return {
props: {
wordsData,
songsData,
searchTerm: context.params.word,
},
};
}
Best practice would definitely be filtering the data on the server, already in your getStaticProps.
So move the filtering there, and only return the data you actually want to use/render.

React component : setState worked but didnt update component

sorry i'm new to React. I'm trying to make a basic social network to learn react.
Context:
When i click on the "like" button, the setState should call the function to update the state of my component, but it is updated only when i refresh the page. I think the ComponentDidUpdate function isn't called like it should. What did i do wrong? Thanks for your help!
Here are the parts of the code :
Like button component:
class Like_Button extends React.Component {
constructor(props) {
super(props);
this.state = {liked : "Like"};
}
isliked(){
fetch("likes_of_user/")
.then(res => res.json())
.then((result) => {
result.map(x => {if(this.props.pk == x.liked_post){this.setState({liked: "Unlike"});}});
})
}
componentDidMount() {
this.isliked();
}
componentDidUpdate(prevProps, prevState) {
if (prevState.liked !== this.state.liked) {
this.isliked();
}
}
render() {
return (
<button className = "buttons" onClick={() => {
var csrftoken = getCookie('csrftoken');
fetch(`like_post/${this.props.pk}`, {method: "POST", headers: {'Accept': 'application/json', 'Content-Type': 'application/json','X-CSRFToken': csrftoken}})
}}>{this.state.liked}</button>
)
}
}
Newsfeed component:
class Newsfeed_comp extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("get_newsfeed/")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map((item ,index) => (
<li className="postbox" key={`${item}${index}`}>
{item.author}
{item.date}
{item.content}
<Like_Button pk={item.id} />
</li>
))}
</ul>
);
}
}
}
ReactDom render:
ReactDOM.render(<Newsfeed_comp />, document.getElementById("newsfeed_view"))
Try something like this:
LikeButton.js
import React, { useEffect, useState } from 'react';
export default function LikeButton({ pk }) {
const [like, setLike] = useState(false);
useEffect(() => {
const fetchLike = async () => {
const res = await fetch("likes_of_user/");
const result = await res.json();
if (result.length > 0) {
setLike(result.find(item => item.liked_post === pk));
}
};
try {
fetchLike();
} catch (error) {
// handle error
}
});
const handleClick = async () => {
const csrftoken = getCookie('csrftoken');
return fetch(`like_post/${pk}`, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken
},
method: 'POST',
});
};
return (
<button className='buttons' onClick={handleClick}>
{like}
</button>
);
};
NewsFeed.js
import React, { useEffect, useState } from 'react';
export function NewsFeed() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
const getNewsFeed = async () => {
const res = await fetch('get_newsfeed/');
const result = await res.json();
setIsLoaded(true);
setItems(result);
};
try {
getNewsFeed();
} catch (error) {
setIsLoaded(true);
setError(error);
}
});
if (error) return <div>Error: {error.message}</div>;
if (isLoaded) return <div>Loading...</div>;
const list = items.map((item) => (
<li className='postbox' key={item.content}>
{item.author}
{item.date}
{item.content}
<LikeButton pk={item.id} />
</li>
));
return <ul>{list}</ul>;
};
App.js
ReactDOM.render(<NewsFeed />, document.getElementById('newsfeed_view'));
Looks like you've reversed your logic, i.e. your button directly updates the data in the backend but does nothing to update component state, so the componentDidUpdate isn't called as you've seen. The refresh is required so the component is remounted and the componentDidMount can fetch the likes data.
Try instead to update local state first, then use componentDidUpdate to issue the side-effect of updating the backend.
constructor(props) {
super(props);
this.state = { liked: true };
}
isliked() {
fetch("likes_of_user/")
.then(res => res.json())
.then((result) => {
result.map(x => {
if (this.props.pk === x.liked_post) {
this.setState({ liked: false });
}
});
})
}
componentDidUpdate(prevProps, prevState) {
if (prevState.liked !== this.state.liked) {
const csrftoken = getCookie('csrftoken');
fetch(
`like_post/${this.props.pk}`,
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
}
);
}
}
<button
className="buttons"
onClick={() => this.setState(
prevState => ({ liked: !prevState.liked })
)}
>
{this.state.liked ? "Liked" : "Unliked"}
</button>

React, the page does not appear

I'm trying to output an article on a new page, but the article on the new page does not appear in the console it's not there, it's empty, how can I fix it.
backend - Ruby on Rails
frontend - React/Redux
The page that displays the article.
task_details.js
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Exit from '../authentication/exit';
import { browserHistory } from 'react-router';
import { getTask } from '../../actions/tasks';
import TasksList from './tasks_list';
import Link from 'react-router'
class TaskDetails extends Component {
componentDidMount () {
let id = this.props.params.id;
this.props.onGetTask(id);
};
render() {
const { task } = this.props
console.log(this.props.location.pathname, "xxxxxxxx")
return (
<div>
{ this.props.task ?
<div className="container">
<h2 className="text-center">{task.title}</h2>
<div className="col-md-2">
<h4 className="pull-right"><i>{task.due_date}</i></h4>
</div>
<div className="clearfix"></div>
<div className="description">
<p>{task.description}</p>
</div>
</div>
:
<div className="container">
<div><h2>Not found</h2></div>
</div>
}
</div>
);
}
};
export default connect(
state => ({
task: state.tasks.item
}),
dispatch => ({
onGetTask: (id) => {
dispatch(getTask(id));
},
})
)(TaskDetails);
The page responsible for the task.
tasks.js
import axios from 'axios';
import cookie from 'react-cookies';
//const API_URL = `https://evening-taiga-79121.herokuapp.com/todos`;
const API_URL = `http://localhost:3000/todos`;
let headers = { 'Content-Type': 'application/json', };
const token = cookie.load('token');
export function fetchTasks(user_id){
return function(dispatch, getState) {
let body = JSON.stringify({ token: token });
headers['Authorization'] = `Bearer ${token}`;
axios.get(`${API_URL}`, { headers, body })
.then(res => {
if (res.status === 200) {
dispatch({ type: 'GET_TASKS', payload: res.data });
}
})
.catch(e => {
console.error("error: ", e);
})
}
}
export function getTask(id) {
return function(dispatch, getState) {
return new Promise((resolve, reject) => {
axios.get(`${API_URL}/${id}`, { headers: headers })
.then(res => {
resolve(res)
dispatch({ type: 'GET_TASK_ID', payload: res.data });
})
.catch(e => {
console.error("error: ", e);
reject(e)
})
})
}
}
export function deleteTask(id){
return function(dispatch, getState) {
let body = { token: token };
axios.delete(`${API_URL}/${id}`, { params: body, headers: headers })
.then(res => {
dispatch({ type: 'DELETE_TASK', payload: id });
})
.catch(id => {
console.error("error", id);
})
}
}
export function addTask(task){
return function(dispatch, getState) {
let body = JSON.stringify({todo: task, token: token});
console.log(body);
axios.post(API_URL, body, { headers: headers })
.then(res => {
dispatch({ type: 'ADD_TASK', payload: res.data });
})
.catch(e => {
console.error(e);
})
}
}
export function completedTask(id, complete){
return function(dispatch, getState) {
if (complete === true) {
complete = false
} else {
complete = true
}
let task = {id: id, completed: complete};
let body = {todo: task, token: token};
axios.patch(`${API_URL}/${task.id}`, body, { headers: headers })
.then(res => {
dispatch({ type: 'COMPLITED_TASK', payload: res.data });
})
.catch(e => {
console.error("error: ", e);
})
}
}
export function sortTasks(sortBy){
return function(dispatch, getState) {
let body = JSON.stringify({ token: token, sortByTitle: sortBy.title, sortByAsc: sortBy.asc });
axios.post(`${API_URL}/sort`, body, { headers: headers })
.then(res => {
console.log(res);
if (res.status === 200) {
dispatch({ type: 'SORT_BY', payload: sortBy });
dispatch({ type: 'FETCH_TODOS_SUCCESS', payload: res.data });
}
})
.catch(e => {
console.error("error: ", e);
})
}
}
export function editTask(task){
return function(dispatch, getState) {
let body = JSON.stringify({todo: task, token: token});
axios.patch(`${API_URL}/${task.id}`, body, { headers: headers })
.then(res => {
dispatch({ type: 'EDIT_TASK', payload: res.data });
})
.catch(e => {
console.error("error: ", e);
})
}
}
The page with which we go to the page with the article.
tasks_index.js
import React, {Component} from 'react';
import { Router, Route, hashHistory } from 'react-router';
import Exit from '../authentication/exit';
import TasksList from './tasks_list';
import New from './new';
import Edit from './edit';
import {connect} from 'react-redux';
import { Link } from 'react-router';
import {fetchTasks, sortTasks} from '../../actions/tasks';
const Tasks_Index = ({user_id, onFetchTasks}) => {
if (user_id) {
onFetchTasks(user_id)
return (
<div>
<div className="container">
<div className="row">
<div className="navbar-header col-md-2">
<a href="#">
<h2 className="pull-right">TASKS</h2>
</a>
</div>
<ul>
<div className="pull-right nav navbar-nav">
<h4><li className=""><Link to="/user/exit">Log out</Link></li></h4>
</div>
</ul>
</div>
</div>
<div className="container">
<div className="row">
<New />
<Edit />
<TasksList />
</div>
</div>
</div>
);
} else
return null;
}
export default connect(
state => ({
user_id: state.user.id,
editId: state.tasks.edit,
sortBy: state.tasks.sortBy
}),
dispatch => ({
onFetchTasks: (user_id) => {
dispatch(fetchTasks(user_id));
}
})
)(Tasks_Index);
Thanks for the help.

Categories