I'm trying to implement a functionality that allows me to check a checkbox through the id. But when I try to check my checkbox, it doesn't show up as checked. I can't make an event, even using event.target. How can I resolve this?
import { useUsers } from '../../services/hooks/useUsers';
import {
Box,
Button,
Checkbox,
Flex,
Heading,
Icon,
Table,
Tbody,
Td,
Th,
Thead,
Tr,
Text,
useBreakpointValue,
Spinner,
Link,
HStack,
useDisclosure,
} from '#chakra-ui/react';
import { Header } from '../../components/Header';
import { NotificationModal } from '../../components/NotificationModal';
import { Sidebar } from '../../components/Sidebar';
import { RiAddLine } from 'react-icons/ri';
import { CgImport } from 'react-icons/cg';
import { TbEdit } from 'react-icons/tb';
import { FaWhatsapp } from 'react-icons/fa';
import { CgNotes } from 'react-icons/cg';
import { Pagination } from '../../components/Pagination';
import NextLink from 'next/link';
import { useEffect, useState } from 'react';
import { queryClient } from '../../services/queryClient';
import { api } from '../../services/api';
export default function UserList() {
const [page, setPage] = useState(1);
const { data, isLoading, isFetching, error } = useUsers(page);
const [user, setUser] = useState([]);
const [ids, setIds] = useState([]);
useEffect(() => {
if (data) {
console.log(data)
setUser(data.users);
}
}, [data]);
function selectUser(e) {
const selectedId = parseInt(e.target.value);
if (ids.includes(selectedId)) {
const newIds = ids.filter((id) => id !== selectedId);
setIds(newIds);
} else {
const newIds = [...ids];
newIds.push(selectedId);
setIds(newIds);
}
}
console.log({selectUser})
async function handlePrefetchUser(userId: string) {
await queryClient.prefetchQuery(
['user', userId],
async () => {
const response = await api.get(`users/${userId}`);
return response.data;
},
{
staleTime: 1000 * 60 * 10,
}
);
}
return (
<Box>
<Header />
<Flex my="6" maxWidth={1480} mx="auto" px="6">
<Sidebar />
<Box flex="1" borderRadius={8} bg="gray.800" p="8">
<Flex mb="8" justify="space-between" align="center">
<Heading size="lg" fontWeight="normal">
Alunos
{!isLoading && isFetching && (
<Spinner size="sm" color="gray.500" ml="4" />
)}
</Heading>
<HStack spacing={4}>
<NextLink href="/users/create" passHref>
<Button as="a" size="sm" fontSize="sm" colorScheme="orange">
<Icon as={RiAddLine} fontSize="20" />
</Button>
</NextLink>
<NotificationModal />
<Button
as="a"
size="sm"
fontSize="sm"
colorScheme="green"
cursor="pointer"
>
<Icon as={CgImport} />
</Button>
</HStack>
</Flex>
{isLoading ? (
<Flex justify="center" align="center">
<Spinner />
</Flex>
) : error ? (
<Flex justify="center">
<Text>Falha ao obter dados dos usuários.</Text>
</Flex>
) : (
<>
<Table colorScheme="whiteAlpha">
<Thead>
<Tr>
<Th px={['4', '4', '6']} color="gray.300" w="8">
<Checkbox colorScheme="orange" />
</Th>
<Th>Usuários</Th>
<Th>Ações</Th>
<Th w="8"></Th>
</Tr>
</Thead>
<Tbody>
{data.users.map((user) => (
<Tr key={user.id}>
<Td px={['4', '4', '6']}>
<Checkbox
colorScheme="orange"
value={user.id}
onChange={selectUser}
isChecked={ids.includes(user.id) ? true : false}
/>
</Td>
Is user.id a number / string of a number eg "1"? because if not, parseInt will return NaN
Even if they are you probably dont need to use parseInt anyway
const selectedId = e.target.value;
Related
i need to ask some question
I have 1 parent(index.js) and 2 childs (JobRequirement.js and JobList.js)
how can i send a data from job requirement to joblist?
here is my code
// JOBREQUIREMENT.JS
const JobRequirement = ({ isOpen, handleSelect }) => {
const [datas, setDatas] = useState([])
const loadData = () => {
axios.get('/bla')
.then((res) => {
setDatas(res.data.data)
})
}
useEffect(() => {
loadData()
}, [])
if (isOpen) {
return (
<Fragment>
<h5 className='mt-3 mb-2'>Job Requirements</h5>
<Row>
{datas.map((data) => (
<Col md='6' lg='4' key={data.id}>
<Card onClick={() => handleSelect(data.id)} className='text-center vertical-align-center mb-3'>
<CardBody>
<CardBody tag='h4'>{data.name}</CardBody>
</CardBody>
</Card>
</Col>
))}
</Row>
</Fragment>
)
} else return (<></>)
}
export default JobRequirement
// INDEX.JS
import { Fragment, useState } from 'react'
import JobRequirement from './JobRequirement'
import JobList from './JobList'
export default function JobRequirements() {
const [jobRequirement, setJobRequirement] = useState(true)
const [jobList, setJobList] = useState(false)
const selectJobRequirement = (data) => {
setJobRequirement(false)
setJobList(true, data)
}
const closeJobList = () => {
setJobRequirement(true)
setJobList(false)
}
return (
<div>
<Fragment>
<JobRequirement isOpen={jobRequirement} handleSelect={selectJobRequirement} />
<JobList isOpen={jobList} close={closeJobList} />
</Fragment>
</div>
)
}
// JOBLIST.JS
import { Fragment } from 'react'
import { Button, Row, Col, Card, CardBody } from 'reactstrap'
import { ChevronLeft } from 'react-feather'
const JobList = ({ isOpen, close, data }) => {
console.log(data)
if (isOpen) {
return (
<Fragment>
<div className='mt-2 mb-2'>
<Button size="sm" className='btn-icon' onClick={() => close()}><ChevronLeft size='15'/></Button> List of Job
</div>
<div>
<Row>
<Col md='6' lg='4'>
<Card className='text-center vertical-align-center mb-3'>
<CardBody>
<CardBody tag='h4'>Hello</CardBody>
</CardBody>
</Card>
</Col>
</Row>
</div>
</Fragment>
)
} else return (<></>)
}
export default JobList
I need to get a {data.id} from jobrequirement.js and use it in joblist.js
thankyou so much
I am having an issue with Navigation Bar jumping to the top after selecting specific page. I want to side bar to stay same position after selecting the page. I found few similar questions here but the given solutions didn't solve my issue. Here the Code.
SideBarItem.js
import React, { useState } from 'react';
import classnames from 'classnames';
import { useRouter } from 'next/router';
import Link from 'next/link';
import useTranslation from 'next-translate/useTranslation';
import { AiOutlineLeft, AiOutlineDown } from 'react-icons/ai';
const SidebarHeader = ({ toggleSideBar, transKey }) => {
const { t } = useTranslation();
return (
<li
name={transKey}
id={transKey}
className={classnames('nav-small-cap', { 'dots-icon': !toggleSideBar })}>
{!toggleSideBar && <i className="mdi mdi-dots-horizontal"></i>}
{toggleSideBar && <span className="hide-menu">{t(transKey)}</span>}
</li>
);
};
const SidebarItem = ({
route,
icon,
toggleSideBar,
transKey,
isHeader,
subs,
}) => {
const { t } = useTranslation();
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
const handleToggle = () => {
setIsOpen(!isOpen);
};
const selectedClassName = router.pathname === route ? 'selected' : null;
return (
<>
{isHeader && (
<SidebarHeader
toggleSideBar={toggleSideBar}
transKey={transKey}
id={transKey}
/>
)}
{!isHeader && (
<li className={classnames('sidebar-item', selectedClassName)}>
<div className="sidebar-link clickable text-white-100 waves-effect waves-dark">
<i className={icon} style={{ color: 'white' }}></i>
{toggleSideBar && (
<div className="arrow-style">
{!subs && (
<Link href={route}>
<a className="hide-menu"> {t(transKey)}</a>
</Link>
)}
{subs && (
<>
<a className="hide-menu" onClick={handleToggle}>
{t(transKey)}
</a>
<div className="sidebar-arrow">
{isOpen ? <AiOutlineDown /> : <AiOutlineLeft />}
</div>
</>
)}
</div>
)}
</div>
{subs && (
<ul
className={classnames('collapse', 'first-level', {
show: isOpen,
})}>
{subs.map((subNavItem) => (
<SidebarItem
key={subNavItem.transKey}
{...subNavItem}
toggleSideBar={toggleSideBar}
/>
))}
</ul>
)}
</li>
)}
</>
);
};
export default SidebarItem;
SidebarLinks.js file
import React from 'react';
import navItems from '#constants/navItems';
import SidebarItem from './SidebarItem';
const SidebarLinks = (props) => {
return (
<nav className="sidebar-nav">
<ul id="sidebarnav" className="in">
{navItems.map((navItem) => (
<SidebarItem key={navItem.transKey} {...navItem} {...props} />
))}
</ul>
</nav>
);
};
export default SidebarLinks;
LayoutWithSidebar.js file
import React from 'react';
import useTranslation from 'next-translate/useTranslation';
import SidebarFooter from '#components/Sidebar/SidebarFooter';
import UserProfile from '#components/Sidebar/UserProfile';
import SidebarLinks from '#components/Sidebar/SidebarLinks';
import Styles from './styles';
const LayoutWithSidebar = ({ toggleSideBar, setToggleSidebar, btn }) => {
const { t } = useTranslation();
const handleEnterMouse = () => {
setToggleSidebar(true);
};
return (
<aside
className={`left-sidebar-style ${
toggleSideBar ? 'open-left-sidebar' : 'left-sidebar'
}`}
onMouseEnter={handleEnterMouse}
data-sidebarbg="skin5">
<div className="scroll-sidebar">
<UserProfile btn={btn} toggleSideBar={toggleSideBar} translation={t} />
<SidebarLinks btn={btn} toggleSideBar={toggleSideBar} translation={t} />
</div>
{(toggleSideBar || btn) && <SidebarFooter />}
<style jsx toggleSideBar={toggleSideBar}>
{Styles}
</style>
</aside>
);
};
export default LayoutWithSidebar;
App.js file
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Row, Col } from 'reactstrap';
import useTranslation from 'next-translate/useTranslation';
import AccountOverview from '#components/Dashboard/AccountOverview';
import Exposure from '#components/Dashboard/Exposure';
import PerformanceStats from '#components/Dashboard/PerformanceStats';
import CommissionAndBalance from '#components/Dashboard/CommissionAndBalance';
import MostRecentConversions from '#components/Dashboard/MostRecentConversions/index';
import Announcement from '#components/Dashboard/Announcement';
import TopPublishers from '#components/Dashboard/TopPublishers';
import ClickByCountries from '#components/Dashboard/TotalVisits/index';
import ClickPerDevice from '#components/Dashboard/OurVisitors/index';
import useShallowEqualSelector from '#hooks/useShallowEqualSelector';
import BaseLayout from '#layouts/BaseLayout';
import { formatNumber } from '#utils';
import routes from '#constants/routes';
import {
fetchAccountOverviewDataAction,
fetchPerformanceStatAction,
fetchAnnouncementAction,
fetchCommissionBalanceAction,
fetchExposuresAction,
fetchRecentConversionAction,
fetchTopPublishersAction,
fetchVisitorDataAction,
} from '#actions';
const Dashboard = () => {
const { t } = useTranslation();
const dispatch = useDispatch();
const [announcementRole, setAnnouncementRole] = useState('advertiser');
const [statFilter, setStatFilter] = useState('day');
const {
accountOverview,
exposures,
visitors,
commissionBalance,
recentConversions,
topPublishers,
performanceStatistics,
} = useShallowEqualSelector(({ stat }) => {
return stat;
});
const {
fetch: { list: announcements, status: announcementFetchStatus },
} = useShallowEqualSelector((state) => state.announcements);
const {
get: { currencyCode },
} = useShallowEqualSelector((state) => state.stat?.recentConversions);
useEffect(() => {
dispatch(fetchCommissionBalanceAction());
dispatch(fetchRecentConversionAction());
}, [dispatch]);
useEffect(() => {
dispatch(fetchAccountOverviewDataAction());
dispatch(fetchExposuresAction());
dispatch(fetchTopPublishersAction());
dispatch(fetchVisitorDataAction());
}, [dispatch]);
useEffect(() => {
dispatch(fetchPerformanceStatAction({ filter: statFilter }));
}, [dispatch, statFilter]);
useEffect(() => {
dispatch(
fetchAnnouncementAction({ role: announcementRole, page: 1, perPage: 4 })
);
}, [dispatch, announcementRole]);
return (
<BaseLayout
metaPageTitle={t('dashboard:pageTitle')}
pageTitle={t('dashboard:pageTitle')}
pageSubtitle={t('dashboard:pageSubtitle')}
breadcrumbPaths={[
{ url: routes.dashboard.url, text: t('common:home') },
{ text: t('dashboard:pageTitle') },
]}>
<div className="container-fluid">
{
<Row>
<Col sm={12}>
<AccountOverview
accountOverview={accountOverview.get.data}
isLoading={accountOverview.get.status === 'loading'}
t={t}
/>
</Col>
</Row>
}
{
<Row>
<Col sm={12}>
<PerformanceStats
isLoading={performanceStatistics.get.status === 'loading'}
setStatFilter={setStatFilter}
statFilter={statFilter}
performanceStatistics={performanceStatistics.get.data}
t={t}
/>
</Col>
</Row>
}
{
<Row>
<Col sm={12}>
<Exposure
exposures={exposures.get.data}
isLoading={exposures.get.status === 'loading'}
t={t}
/>
</Col>
</Row>
}
{
<Row>
<Col sm={12}>
<CommissionAndBalance
commissionBalance={commissionBalance.get.data}
isLoading={commissionBalance.get.status === 'loading'}
t={t}
/>
</Col>
</Row>
}
<Row>
<Col sm={12}>
<MostRecentConversions
isLoading={recentConversions.get.status === 'loading'}
recentConversions={recentConversions.get.data}
t={t}
currencyCode={currencyCode}
/>
</Col>
</Row>
<Row>
<Col sm={12}>
<div className="card-deck mb-4">
{
<Announcement
announcements={announcements}
announcementRole={announcementRole}
isLoading={announcementFetchStatus === 'loading'}
setAnnouncementRole={setAnnouncementRole}
t={t}
/>
}
<TopPublishers
isLoading={topPublishers.get.status === 'loading'}
topPublishers={topPublishers.get.data}
t={t}
formatNumber={formatNumber}
format
/>
</div>
</Col>
</Row>
{
<Row>
<Col sm={6}>
<ClickByCountries
isLoading={visitors.get.status === 'loading'}
totalVisitors={visitors.get.data?.totalVisitors}
t={t}
/>
</Col>
<Col sm={6}>
<ClickPerDevice
isLoading={visitors.get.status === 'loading'}
ourVisitors={visitors.get.data?.ourVisitors}
t={t}
/>
</Col>
</Row>
}
</div>
</BaseLayout>
);
};
export default Dashboard;
It would be great if you can assist.
P.S. I already looked through some answers here but it didn't work for me.
PLS check video link below
https://www.youtube.com/shorts/4xzlBfhQcKQ
From the video that you showed and the code you shared it seems that you wrapped your sidebar along with the entire application and pages components. If you want to avoid "rerendering" the sidebar, which is the thing that applies the "go to the top" effect, you should unwrap the layout with sidebar from the route changing, this will prevent this behaviour.
This is where i generate the token
import React, { useState, useEffect } from 'react';
import { Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button } from '#material-ui/core';
import { commerce } from '../../../lib/commerce';
import useStyles from './styles';
import AddressForm from '../AddressForm';
import PaymentForm from '../PaymentForm';
const steps = ['Shipping address', 'Payment details'];
const Checkout = ({ cart }) => {
const [activeStep, setActiveStep] = useState(0);
const [checkoutToken, setCheckoutToken] = useState(null);
const classes = useStyles();
useEffect(() => {
if (cart.id) {
const generateToken = async () => {
try {
const token = await commerce.checkout.generateToken(cart.id, { type: 'cart' });
setCheckoutToken(token)
} catch (error){
console.log(error);
}
};
generateToken();
}
}, [cart]);
const Confirmation = () => (
<div>
Confirmation
</div>
)
const Form = () => activeStep === 0
? <AddressForm checkoutToken={checkoutToken} />
: <PaymentForm />
return (
<>
<div className={classes.toolbar} />
<main className={classes.layout} >
<Paper className={classes.paper}>
<Typography variant='h4' align='center'>Checkout</Typography>
<Stepper activeStep={activeStep} className={classes.stepper}>
{steps.map((step) => (
<Step key={step}>
<StepLabel>{step}</StepLabel>
</Step>
))}
</Stepper>
{activeStep === steps.length ? <Confirmation /> : checkoutToken && <Form />}
</Paper>
</main>
</>
)
}
export default Checkout
Here is my App.js
import React, { useState, useEffect, Fragment } from 'react'
import { commerce } from './lib/commerce';
import { Products, Navbar, Cart, Checkout } from './components';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
const App = () => {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState({});
const fetchProducts = async () => {
const { data } = await commerce.products.list();
setProducts(data);
}
const fetchCart = async () => {
setCart(await commerce.cart.retrieve())
}
const handleAddToCart = async ( productId, quantity) =>{
const { cart } = await commerce.cart.add(productId, quantity);
setCart(cart);
}
const handleUpdateCartQty = async (productId, quantity) => {
const { cart } = await commerce.cart.update(productId, { quantity });
setCart(cart);
}
const handleRemoveFromCart = async (productId) => {
const { cart } = await commerce.cart.remove(productId);
setCart(cart);
}
const handleEmptyCart = async () => {
const { cart } = await commerce.cart.empty();
setCart(cart);
}
useEffect(() => {
fetchProducts();
fetchCart();
}, []);
return (
<Router>
<div>
<Navbar totalItems={cart.total_items} />
<Routes>
<Route exact path='/' element={<Products products={products} onAddToCart={handleAddToCart} />} />
<Route exact path='/cart' element={<Cart cart={cart} handleUpdateCartQty={handleUpdateCartQty} handleAddToCart={handleAddToCart} handleRemoveFromCart={handleRemoveFromCart} handleEmptyCart={handleEmptyCart} />} />
<Route exact path='/checkout' element={ <Checkout cart={cart} />} />
</Routes>
</div>
</Router>
)
}
export default App;
And here is my cart.jsx incase their is anything relevant there
import React from 'react'
import { Container, Typography, Button, Grid} from '#material-ui/core';
import { Link } from 'react-router-dom';
import useStyles from './styles';
import CartItem from './CartItem/CartItem';
const Cart = ({ cart, handleUpdateCartQty, handleRemoveFromCart, handleEmptyCart }) => {
const classes = useStyles();
const EmptyCart = () => (
<Typography variant='subtitle1'>
You have no items in your shopping cart.
<Link to='/' className={classes.link}>Add Items!</Link>
</Typography>
);
const FilledCart = () => (
<>
<Grid container spacing={3}>
{ cart.line_items.map((item) => (
<Grid item xs={12} sm={4} key={item.id}>
<CartItem item={item} onUpdateCartQty={handleUpdateCartQty} onRemoveFromCart={handleRemoveFromCart} />
</Grid>
))}
</Grid>
<div className={classes.cardDetails}>
<Typography variant='h4'>
Subtotal: {cart.subtotal.formatted_with_symbol}
<div>
<Button className={classes.emptyButton} size='large' type='button' variant='contained' color='secondary' onClick={handleEmptyCart}>
Empty Cart
</Button>
<Button component={Link} to='/checkout' className={classes.checkoutButton} size='large' type='button' variant='contained' color='primary'>
Checkout
</Button>
</div>
</Typography>
</div>
</>
);
// Wait for cart to load items
if(!cart.line_items){
return '...loading';
}
return (
<Container>
<div className={classes.toolbar} />
<Typography className={classes.title} varaint='h3' gutterBottom >Your Shopping Cart</Typography>
{ !cart.line_items.length ? <EmptyCart /> : <FilledCart />}
</Container>
)
}
export default Cart
[error messages][1]
[1]: https://i.stack.imgur.com/vlard.png
Warning: Expected onSubmit listener to be a function, instead got a
value of string type. form
FormProvider#http://localhost:3000/static/js/bundle.js:76722:7
AddressForm#http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper#http://localhost:3000/static/js/bundle.js:12332:17
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout#http://localhost:3000/static/js/bundle.js:1332:7
Routes#http://localhost:3000/static/js/bundle.js:67209:7 div
Router#http://localhost:3000/static/js/bundle.js:67146:7
BrowserRouter#http://localhost:3000/static/js/bundle.js:65952:7
App#http://localhost:3000/static/js/bundle.js:347:82
Warning: A component is changing a controlled input to be
uncontrolled. This is likely caused by the value changing from a
defined to undefined, which should not happen. Decide between using a
controlled or uncontrolled input element for the lifetime of the
component. More info: https://reactjs.org/link/controlled-components
input SelectInput#http://localhost:3000/static/js/bundle.js:13482:19
div InputBase#http://localhost:3000/static/js/bundle.js:8257:25
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25
Input#http://localhost:3000/static/js/bundle.js:9146:26
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25
Select#http://localhost:3000/static/js/bundle.js:13182:26
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 div
Grid#http://localhost:3000/static/js/bundle.js:7352:29
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 div
Grid#http://localhost:3000/static/js/bundle.js:7352:29
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 form
FormProvider#http://localhost:3000/static/js/bundle.js:76722:7
AddressForm#http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper#http://localhost:3000/static/js/bundle.js:12332:17
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout#http://localhost:3000/static/js/bundle.js:1332:7
Routes#http://localhost:3000/static/js/bundle.js:67209:7
I want when I onClick element row, that show coin.id that element in console.log
import React, { useState, useEffect } from "react";
import { Col, Image, Row } from "react-bootstrap";
import "./Company.scss";
// * api
import { getCoin } from "../services/api";
// *spinner
import Loader from "./Loader";
const Company = () => {
const [selectedCoin, setSelectedCoin] = useState(null);
const [coins, setCoins] = useState([]);
useEffect(() => {
const fetchAPI = async () => {
const data = await getCoin();
setCoins(data);
};
fetchAPI();
}, []);
return (
<>
{coins.length > 0 ? (
coins.map((coin) => (
<Row
className={
selectedCoin === coin.id
? "p-2 border-top d-flex align-items-center company-list-single-active"
: "p-2 border-top d-flex align-items-center company-list-single"
}
onClick={() => {
setSelectedCoin(coin.id);
}}
key={coin.id}
>
<Col xxl="2" xl="2" lg="3" md="3" sm="2" xs="2">
<Image
src={coin.image}
alt={coin.name}
className="coin-image mx-2"
fluid
/>
</Col>
<Col>
<span>{coin.name}</span>
</Col>
</Row>
))
) : (
<Loader />
)}
</>
);
};
export default Company;
screenshot project
If you wish to add another call (like console.log()) in the anonymous function for the onClick event handler, you can
onClick={() => {
console.log(coin.id);
setSelectedCoin(coin.id);
}}
I am new to React. Currently, I am doing API fetch and displaying it in a table and adding edit delete in that table. I am successfully fetching API and I can add a new row along with API data, but I don't know how to edit and delete it. I have seen some questions but my code structure is different so I am unable to find the answer. Does any help please?
here is my code,
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { makeStyles,withStyles } from '#material-ui/core/styles';
import Fab from '#material-ui/core/Fab';
import AddIcon from '#material-ui/icons/Add';
import EditIcon from '#material-ui/icons/Edit';
import TextField from '#material-ui/core/TextField';
import Dialog from '#material-ui/core/Dialog';
import DialogActions from '#material-ui/core/DialogActions';
import DialogContent from '#material-ui/core/DialogContent';
import DialogContentText from '#material-ui/core/DialogContentText';
import DialogTitle from '#material-ui/core/DialogTitle';
import Button from '#material-ui/core/Button';
const useStyles = theme => ({
fab: {
margin: theme.spacing(1),
},
extendedIcon: {
marginRight: theme.spacing(1),
},
});
const Post = ({ body }) => {
return (
<table className=" table-striped">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Content</th>
</tr>
</thead>
<tbody>
{body.map(post => {
const { _id, title, content } = post;
return (
<tr key={_id}>
<td> {_id!=''?_id: '-'}</td>
<td> {title!='' ?title: '-'}</td>
<td> {content!=''?content: '-'}</td>
<hr />
</tr>
);
})}
</tbody>
</table>
);
};
class App extends React.Component {
state = {
isLoading: true,
posts: [],
error: null,
open:false,
newData:[
{
_id:'',
title:'',
content:''
}
]
};
fetchPosts() {
const axios = require('axios');
axios
.get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json")
.then(response => {
this.setState({
posts: response.data.posts,
isLoading: false,
})
//)
} )
}
componentDidMount() {
this.fetchPosts();
}
handleClickOpen = () =>
this.setState({
open:true
})
;
handleClose = () =>
this.setState({
open:false
})
;
// handleClick = () =>
// {
// {this.handleClickOpen}
// {this.addItem}
// }
// ;
addItem = () =>
{
var temp = [];
var tempPosts = this.state.posts;
var newData = this.state.newData[0];
console.log(this.state.newData)
if(this.state.newData[0]._id && this.state.newData[0].title && this.state.newData[0].content){
tempPosts.push(newData);
console.log(tempPosts)
this.setState({posts: tempPosts})
}
}
render() {
const { isLoading, posts } = this.state;
return (
<React.Fragment>
<h1>React Fetch - Blog</h1>
<div>
<Button variant="outlined" color="primary" onClick=
{this.handleClickOpen}
>
Add
</Button>
<Dialog open={this.state.open} onClose={this.handleClose} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Subscribe</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
id="_id"
label="id"
value={this.state.newData._id}
onChange={(e)=> {
let{ newData } = this.state;
newData[0]._id=e.target.value;
this.setState({newData})
}}
type="text"
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="title"
label="title"
value={this.state.newData.title}
onChange={(e)=> {
let{newData} =this.state;
newData[0].title=e.target.value;
this.setState({newData})
}}
type="text"
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="content"
label="content"
value={this.state.newData.content}
onChange={(e)=> {
let{newData} =this.state;
newData[0].content=e.target.value;
this.setState({newData})
}}
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button
onClick={() => {
this.addItem()
this.handleClose()
}}
color="primary">
Add
</Button>
<Button onClick={this.handleClose} color="primary">
cancel
</Button>
</DialogActions>
</Dialog>
</div>
<hr />
{!isLoading ? <Post body={posts} /> : <h3>Loading...</h3>}
</React.Fragment>
);
}
}
export default withStyles(useStyles)(App);