I am using ReactJs and I am trying to create CRUD app that will be able to delete, display and add item to JSON file. With ReactJs I am also using Redux. I am trying to learn how to use ReactJs and Redux together.
JSON file will act like server.
This is my structure for now:
index.js
const logger = createLogger();
const store = createStore(combineReducers({roomReducer}), {}, applyMiddleware(logger));
ReactDOM.render(
<Provider store = {store}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>,
document.querySelector("#root")
);
App.js
export default class App extends React.Component {
render() {
return (
<div>
<Route path="/" exact component={LandingPage} />
</div>
)
}
}
REDUCERS
index.js
import {combineReducers} from 'redux';
import rooms from '../templates/rooms/Rooms';
const roomsReducer = combineReducers({
rooms
});
export default roomsReducer;
roomReducer.js
const initialState = {
rooms: []
};
export default function cardReducer(state = initialState, action) {
switch (action.type){
case 'ADD_ROOM':
return {
...state,
rooms: [
...state.rooms,
action.rooms
]
}
case 'REMOVE_ROOM':
//not sure how to do it
case 'FETCH_ROOMS':
return Object.assign({}, state, {
cards: action.rooms
});
default:
return state;
}
}
ACTIONS
roomActions.js
export function fetchRooms(){
return {
type: 'FETCH_ROOMS'
}
}
export function addRoom(){
return {
type: 'ADD_ROOM'
}
}
export function removeRoom(id){
return {
type: 'REMOVE_ROOM',
id: id
}
}
db.json
{
"cards": [
{
"id": 0,
"image": "http://placehold.it/400x300",
"title": "CATEGORY 0",
"numberGuests": "Placeholder 0",
"type": "Single"
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 6
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 7
}
]
}
This code is what I have came up by now. I have created store in my index.js file and connected it to my rooms.js component
class Rooms extends React.Component{
render(){
return(
<div>
hello
</div>
);
}
}
const mapStateToProps = (state) => {
return{
room: state.roomReducer
};
};
export default connect(mapStateToProps)(Rooms);
I hope I did it correctly. I am not sure how to now add, delete or list rooms that I have already in db.json file.
Any advice or guideline is highly appreciated.
let dbjson = {
"cards": [
{
"id": 0,
"image": "http://placehold.it/400x300",
"title": "CATEGORY 0",
"numberGuests": "Placeholder 0",
"type": "Single"
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 6
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 7
}
]
};
let state = {};
//You have cards in state
state['rooms'] = dbjson.cards;
// add room
let roomItem = {
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 8
};
let rooms = [...state.rooms,roomItem];
state['rooms'] = rooms;
//dispatch
// remove room by index
let index = 1;
let roomstodelete = [...state.rooms];
roomstodelete.splice(1,index);
state['rooms'] = roomstodelete;
//dispatch
// remove room by id
let roomstodeleteByid = [...state.rooms].filter(vl=>vl.id!==8);
state['rooms'] = roomstodeleteByid;
//dispatch
Related
Here is my code
This is Service.js file
import React, { useEffect, useState } from 'react';
import Home from './Home';
const Service = () => {
const [products, setProducts] = useState([]);
useEffect( ()=>{
fetch('data.json')
.then(res => res.json())
.then(data => setProducts(data))
}, [])
return (
<div>
{
products.map(product => <Home product={product}></Home>)
}
</div>
);
};
export default Service;
Where I want to send data
import React from 'react';
const Home = (props) => {
const {name, img, extra} = props.product;
return (
<div>
<h1>Name: {name} </h1>
</div>
);
};
export default Home;
Database
[
{
"id": 1,
"extra": "mahfuzur",
"name": "Professor Dr. Md. Mahfuzur Rahman",
"title": "Dean, Faculty of Engineering & Technology",
"mobile": "09602666651 09602666652",
"email": "dean_et#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FChairperson.jpg"
},
{
"id": 2,
"name": "Prof. Dr. Engr. Aminul Hoque",
"extra": "aminul Hoque",
"title": "Professor",
"mobile": "09602666651, 09602666652",
"email": "ahoque.eee#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FAminulHoque.jpg"
},
{
"id": 3,
"extra": "golam robbani",
"name": "Professor Dr. Mirza Golam Rabbani",
"title": "Chairperson, Department of Electrical & Electronic Engineering",
"mobile": "09602666651, 09602666652 ",
"email": "mgrabbani#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FRabbaniChairperson_EEE.jpg"
},
{
"id": 4,
"extra": "mahfuz",
"name": "Mr. Muhammad Mahfuz Hasan",
"title": "Chairperson and Assistant Professor, Department of Computer Science and Engineering",
"mobile": "9602666651, 09602666652",
"email": "mhasan#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FMilonSir.jpg"
},
{
"id": 5,
"extra": "iqbal mahmud",
"name": "Dr. Iqbal Mahmud",
"title": "Assistant Professor and Hostel Super (Male Hostel)",
"mobile": "0909602666651, 09602666652",
"email": "iqbal.et#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FIqbal.et.jpg"
},
{
"id": 6,
"extra": "nargis begam",
"name": "Ms. Nargis Begam",
"title": "Lab Manager(Technical)",
"mobile": "09602666651, 09602666652",
"email": "nargis#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FNargis.jpg"
}
]
I fetch the data and I send it via product={product}in home section where I want to send. But when I send the data Home section didn't find any data. Is there any possibility of compiler error? or what is the main problem I didn't catch? Please help me.
My colleague and I are creating a simple directory app for departments and hit a roadblock - we can't successfully post the data from our database after trying to implement the data from our database directly into the app.
We were able to use dummy data for proof of concept and now having a difficult time trying to get the real data to show up. The data is being retrieved and parsed as a JS Object format which should be exactly what we were using before, however we're getting the error of:
Line 42:22: 'person' is not defined. no-undef
Here's what we have for our code:
App.js
import React from 'react';
import '../scss/App.css';
import PeopleList from './components/PeopleList';
import Accordion from "./components/Accordion";
import "../scss/main.scss";
class App extends React.Component {
render() {
return (
<div id="app">
<h1>Address Book</h1>
<PeopleList /> {/*The component we're having issues with */}
<Accordion addresses={addresses} />
</div>
)
}
}
export default App;
PeopleList.js
import React from 'react';
import axios from 'axios';
import '../../scss/App.css';
// let person = [
// {
// "division": "Town 1",
// "deptName": "Department 1",
// "name": "Pluto",
// "title": "Title 1",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 2",
// "deptName": "Department 2",
// "name": "Pluto",
// "title": "Title 2",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 3",
// "deptName": "Department 3",
// "name": "Pluto",
// "title": "Title 3",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 4",
// "deptName": "Department 4",
// "name": "Pluto",
// "title": "Title 4",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 5",
// "deptName": "Department 5",
// "name": "Pluto",
// "title": "Title 5",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 6",
// "deptName": "Department 6",
// "name": "Pluto",
// "title": "Title 6",
// "phone1": "(123) 456-7890",
// },
// ];
class PeopleList extends React.Component {
state = {
person: []
}
componentDidMount() {
axios({
method: 'GET',
url: '/phonebook/all'
})
.then((res) => {
console.log(res.data)
const person = res.data;
console.log(person)
const obj = JSON.parse(person);
console.log(obj)
this.setState({ person });
})
};
constructor() {
super();
this.state = {
search: ''
}
};
render() {
return (
<>
<div className="people-list">
<ul className="list">
{person.map((p)=> {
return (
<li>
<p>
{p.name} <br />
{p.title} <br />
{p.phone1} <br />
{p.division}
</p>
</li>
)
})}
</ul>
</div>
</>
)
}
}
export default PeopleList
With the given axios call, we're under the impression person is being defined as a JS Object class just like our dummy data, but the error message states otherwise. We're successfully able to console.log() the data per the calls during the axios call when we comment out the person.map() part in the return so we know the data is being returned, but not sure what we're missing to have the data be returned on the client side. Any help on this is greatly appreciated.
Updated the constructor and axios call - our data is now returning!!
PeopleList.js
import React from 'react';
import axios from 'axios';
import '../../scss/App.css';
// let person = [
// {
// "division": "Town 1",
// "deptName": "Department 1",
// "name": "Pluto",
// "title": "Title 1",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 2",
// "deptName": "Department 2",
// "name": "Pluto",
// "title": "Title 2",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 3",
// "deptName": "Department 3",
// "name": "Pluto",
// "title": "Title 3",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 4",
// "deptName": "Department 4",
// "name": "Pluto",
// "title": "Title 4",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 5",
// "deptName": "Department 5",
// "name": "Pluto",
// "title": "Title 5",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 6",
// "deptName": "Department 6",
// "name": "Pluto",
// "title": "Title 6",
// "phone1": "(123) 456-7890",
// },
// ];
class PeopleList extends React.Component {
// state = {
// person: []
// }
componentDidMount() {
axios({
method: 'GET',
url: '/phonebook/all'
})
.then((res) => {
this.setState({ person:res.data });
})
};
constructor() {
super();
this.state = {
search: '',
person: []
}
};
render() {
return (
<>
<div className="people-list">
<ul className="list">
{this.state.person.map((p)=> {
return (
<li>
<p>
{p.name} <br />
{p.title} <br />
{p.phone1} <br />
{p.division}
</p>
</li>
)
})}
</ul>
</div>
</>
)
}
}
export default PeopleList
i am trying to solve this problem is, whenever user will click on category title then user will redirect to another page and will see the product_set data as per category id or slug.
i am probably new to ReactJs, it would be great if anybody could help me out what i am trying to solve is. thank you so much in advance.
end point url: "http://localhost:8000/api/p_category"
Api data:
[
{
"id": 1,
"title": "category01",
"slug": "category01",
"description": "",
"image": "http://localhost:8000/media/cat2_KpMV1YQ.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product01",
"id": 1,
"title": "product01",
"slug": "product01",
"image": "http://localhost:8000/media/product2_EMWEgQI.png",
"price": 5,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
]
},
{
"id": 3,
"title": "category03",
"slug": "category03",
"description": "category03 desc..",
"image": "http://localhost:8000/media/cat3_9dal1uP.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product03",
"id": 3,
"title": "product03",
"slug": "product03",
"image": "http://localhost:8000/media/product5.png",
"price": 3,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
{
"url": "http://localhost:8000/api/p/product06",
"id": 5,
"title": "product06",
"slug": "product06",
"image": "http://localhost:8000/media/product6_rkmAlce.png",
"price": 12,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
}
]
}
]
You can do like this,
import { React } from "react";
class categoryListExample extends React.Component{
state={
categoryList:[],
category:''
}
async componentDidMount(){
let res=await fetch("http://localhost:8000/api/p_category")
//assuming you are getting data in response.data
this.setState({categoryList:res.data})
}
categoryChangeHandler=(category)=>{
this.setState({category})
}
render(){
const {categoryList,category}=this.state
if (categoryList.length>0) {
return(
<div>
<ul>
{categoryList.map(category=><li key={category.id} onClick={this.categoryChangeHandler}>{category.title}</li>)}
</ul>
<CategoryComponent category={category.product_set}/>
</div>
)
} else {
return(
<div>
Loading...
</div>
)
}
}
}
export default categoryListExample;
I'm trying to get to nested layers, like "title", in JSON data. However, first property is variable and the : character within isn't helping either
"ISBN:nnnnnnnnnnnn"
Mapping values to component to be destructured using:
renderBooks()
{
return this.state.books.map((book, index) =>
<BookDetail key={index} book={book} />);
}
render()
{
console.log(this.state);
return (
<ScrollView style={{ flex: 1 }}>
{this.renderBooks()}
</ScrollView>
);
}
Component:
const BookDetail = ({ book }) =>
{
const { title, author,... } = book;
return (
<Card>
<CardSection>
<View style={styles.headerContentStyle}>
<Text style={headerTextStyle}>{title}</Text>
<Text>{author}</Text>
</View>
</CardSection>
</Card>
);
};
JSON:
[
{
"ISBN:9780192853462": {
"publishers": [
{
"name": "Oxford University Press, USA"
}
],
"identifiers": {
"isbn_13": [
"9780192853462"
],
"openlibrary": [
"OL7384519M"
],
"isbn_10": [
"0192853465"
],
"librarything": [
"49548"
],
"goodreads": [
"334271"
]
},
"subtitle": "A Very Short Introduction (Very Short Introductions)",
"title": "Social and Cultural Anthropology",
"url": "https://openlibrary.org/books/OL7384519M/Social_and_Cultural_Anthropology",
"number_of_pages": 168,
"cover": {
"small": "https://covers.openlibrary.org/b/id/119856-S.jpg",
"large": "https://covers.openlibrary.org/b/id/119856-L.jpg",
"medium": "https://covers.openlibrary.org/b/id/119856-M.jpg"
},
"subjects": [
{
"url": "https://openlibrary.org/subjects/ethnology",
"name": "Ethnology"
}
],
"publish_date": "April 7, 2000",
"key": "/books/OL7384519M",
"authors": [
{
"url": "https://openlibrary.org/authors/OL656666A/John_Monaghan",
"name": "John Monaghan"
},
{
"url": "https://openlibrary.org/authors/OL2662612A/Peter_Just",
"name": "Peter Just"
}
],
"ebooks": [
{
"formats": {},
"preview_url": "https://archive.org/details/socialculturalan00mona",
"availability": "restricted"
}
]
}
}
You could make your own copy of the book object, all the book information is wrapped inside the ISBN attribute, personaly I would have made it a simple field inside the book object.
let data = {
"ISBN:9780192853462": {
"publishers": [
{
"name": "Oxford University Press, USA"
}
],
"identifiers": {
"isbn_13": [
"9780192853462"
],
"openlibrary": [
"OL7384519M"
],
"isbn_10": [
"0192853465"
],
"librarything": [
"49548"
],
"goodreads": [
"334271"
]
},
"subtitle": "A Very Short Introduction (Very Short Introductions)",
"title": "Social and Cultural Anthropology",
"url": "https://openlibrary.org/books/OL7384519M/Social_and_Cultural_Anthropology",
"number_of_pages": 168,
"cover": {
"small": "https://covers.openlibrary.org/b/id/119856-S.jpg",
"large": "https://covers.openlibrary.org/b/id/119856-L.jpg",
"medium": "https://covers.openlibrary.org/b/id/119856-M.jpg"
},
"subjects": [
{
"url": "https://openlibrary.org/subjects/ethnology",
"name": "Ethnology"
}
],
"publish_date": "April 7, 2000",
"key": "/books/OL7384519M",
"authors": [
{
"url": "https://openlibrary.org/authors/OL656666A/John_Monaghan",
"name": "John Monaghan"
},
{
"url": "https://openlibrary.org/authors/OL2662612A/Peter_Just",
"name": "Peter Just"
}
],
"ebooks": [
{
"formats": {},
"preview_url": "https://archive.org/details/socialculturalan00mona",
"availability": "restricted"
}
]
}
};
//let isbn = Object.keys(obj).find(item => item.match(/ISBN:\d/));
const destructureBook = (obj) => {
let book = {};
Object.keys(obj).map(function(key) {
if(key.match(/ISBN:\d/)) book['isbn'] = key;
Object.keys(obj[key]).map(field => book[field] = obj[key][field]);
});
return book;
}
// destructure the return of the function
const {isbn, title, publish_date } = destructureBook(data);
console.log(isbn, title, publish_date)
I have 2 array of object, one is the preloaded list, one is the selected items. My problem is couldn't make the selected items checked on checkboxes.
https://jsfiddle.net/8usvfzv9
class HelloWidget extends React.Component {
constructor(props) {
super(props);
this.list = [{
"id": "exhibitions",
"name": "Exhibitions"
}, {
"id": "festivals_n_concerts",
"name": "Festivals & Concerts"
}, {
"id": "grand_opening",
"name": "Grand Opening"
}, {
"id": "meeting",
"name": "Meeting"
}, {
"id": "party",
"name": "Party"
}, {
"id": "product_launches",
"name": "Product Luanches"
}, {
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}, {
"id": "trade_show",
"name": "Trade Show"
}]
this.selectedList = [{
"id": "grand_opening",
"name": "Grand Opening",
"space_event_id": "grand_opening"
}, {
"id": "trade_show",
"name": "Trade Show",
"space_event_id": "trade_show"
}]
}
render() {
return (<div>
{this.list.map(obj => <div><br /><input
key={obj.name}
checked={this.selectedList.findIndex(o => o.id === obj.id)}
type="checkbox" >{obj.name}</input></div>)}
</div>
)
}
}
I think this line is wrong
checked={this.selectedList.findIndex(o => o.id === obj.id)}
base on the output result. Any clue how to use findIndex?
As 'checked' prop only works with boolean and findIndex returns number, you can modify as below:
checked={this.selectedList.findIndex(o => o.id === obj.id) !== -1}