Not able to fetch data from API using React Router - reactjs

I am trying to make a demo project using a free API available in web. I am trying to fetch using js fetch method and I am using the latest react-router-dom package
App.js is setting up the route with appropriate loaders
App.js
import "./App.css";
import Root from "./layouts/Root";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import Posts from "./pages/Posts";
import { loader as allPostsLoader } from "./pages/Posts";
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
Children: [{ index: true, element: <Posts />, loader: allPostsLoader }],
},
]);
function App() {
return (
<>
<RouterProvider router={router} />
</>
);
}
export default App;
Posts.js
import { json } from "react-router-dom";
import { useLoaderData } from "react-router-dom";
import PostsList from "../components/PostsList";
const Posts = () => {
const data = useLoaderData();
console.log(data);
return (
<PostsList posts={data} />
);
};
export default Posts;
export const loader = async () => {
const response = await fetch("https://dummyapi.io/data/v1/post", {
method: "GET",
headers: new Headers({
"app-id": "63e0971cd1c871fb16613cc4",
}),
body:undefined
});
if (!response.ok) {
throw json({ message: "Count not fetch data!!" }, { status: 500 });
}
return response;
};
PostsList.js
const PostsList = ({ posts }) => {
return (
<div className="all-post">
<h1>All Posts</h1>
<div className="posts-wrapper">
{posts.map((post) => {
<div key={post.id} className="post">
<div className="image">
<img src={post.image} alt="" />
</div>
<h2>{post.text}</h2>
<p>Publish Date: {post.publishDate}</p>
</div>
})}
;
</div>
</div>
);
};
export default PostsList;
Response from API
{
"data": [
{
"id": "60d21b4667d0d8992e610c85",
"image": "https://img.dummyapi.io/photo-1564694202779-bc908c327862.jpg",
"likes": 43,
"tags": [
"animal",
"dog",
"golden retriever"
],
"text": "adult Labrador retriever",
"publishDate": "2020-05-24T14:53:17.598Z",
"owner": {
"id": "60d0fe4f5311236168a109ca",
"title": "ms",
"firstName": "Sara",
"lastName": "Andersen",
"picture": "https://randomuser.me/api/portraits/women/58.jpg"
}
},
{
"id": "60d21b4967d0d8992e610c90",
"image": "https://img.dummyapi.io/photo-1510414696678-2415ad8474aa.jpg",
"likes": 31,
"tags": [
"snow",
"ice",
"mountain"
],
"text": "ice caves in the wild landscape photo of ice near ...",
"publishDate": "2020-05-24T07:44:17.738Z",
"owner": {
"id": "60d0fe4f5311236168a10a0b",
"title": "miss",
"firstName": "Margarita",
"lastName": "Vicente",
"picture": "https://randomuser.me/api/portraits/med/women/5.jpg"
}
}
],
"total": 873,
"page": 0,
"limit": 20
}
I am not able to see the app call in the Network section and now errors are shown as well.

Related

I can't retrieve consistent information from my solidity smart contract using react and web3

I try to interact with functions in my deployed contract using web3. It works fine to get information from metamask but it seems to return truncated value with my smart contract (?).
The request with await web3.eth.getAccounts() wotks fine, but the requests for the smart contract MyDeposit.methods.getBalance().call() and MyDeposit.methods.account().call()seem inconsistent.
here is a screen shot of html rendering
here is a screen sot of my console
I retrieve well my account (0x3B8F16325799ce799555243418df22C5c8e81f48) but I should have retrieved also 9000000000001 for MyDeposit.methods.getBalance and (0x3B8F16325799ce799555243418df22C5c8e81f48) for MyDeposit.methods.account. however, I just got (9) for MyDeposit.methods.getBalance and (0) for MyDeposit.methods.account. It looks like if only the first digit of good response was returned.
would be great if anyone could help. Txs
here is my code :
import React, { Component } from "react";
import Web3 from "web3";
import "./App.css";
import { TODO_LIST_ABI, TODO_LIST_ADDRESS, TODO_ENTER_YOUR_KEY } from "./config";
class App extends Component {
async UNSAFE_componentWillMount() {
await this.loadWeb3();
await this.loadBlockchainData();
}
async loadWeb3() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
await window.ethereum.enable();
} else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
} else {
window.alert("No ethereum broswer detected! You can check out MetaMask!");
}
}
async loadBlockchainData() {
const web3 = new Web3(
Web3.givenProvider ||
"https://goerli.infura.io/v3/" + TODO_ENTER_YOUR_KEY
);
const accounts = await web3.eth.getAccounts();
this.setState({ account: accounts[0] });
const MyDeposit = new web3.eth.Contract(TODO_LIST_ABI, TODO_LIST_ADDRESS);
console.log(MyDeposit);
const owners = await MyDeposit.methods.owner().call();
this.setState({ owner: owners[0] });
console.log("this.state.owner : " + this.state.owner);
await MyDeposit.methods.sendEther().call();
let balances = []
balances = await MyDeposit.methods.getBalance().call();
console.log(balances[0])
this.setState({ balance: balances[0] });
console.log(this.state.balance);
console.log("this.state.balance : " + this.state.balance);
}
constructor(props) {
super(props);
this.state = {
account:[],
balance: [],
owner: []
};
}
render() {
return (
<div>
<div className="container-fluid">
<div className="row">
<main
role="main"
className="col-lg-12 d-flex justify-content-center"
>
<div id="loader" className="text-center">
<p className="text-center">On progress...</p>
</div>
<div id="content">
<p> the account is : {this.state.account} </p>
<p> the balance is : {this.state.balance} </p>
<p> the owner is : {this.state.owner} </p>
<ul id="completedTaskList" className="list-unstyled"></ul>
</div>
</main>
</div>
</div>
</div>
);
}
}
export default App;
here is the config.js with smart contract ABI
export const TODO_LIST_ADDRESS = "0xe78a5c60fa13BBB677d4c1D37a007ed59bE5Ca2e";
export const TODO_ENTER_YOUR_KEY = "enter your infura key for testing";
export const TODO_LIST_ABI = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getBalance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "owner",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "sendEther",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address payable",
"name": "recipient",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferEther",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
}
]
owner and balancese had to be declared in the array. It's now OK.
I wrote:
const owners = [await MyDeposit.methods.owner().call()];
const balances = [await MyDeposit.methods.getBalance().call()];
instead of previous:
const owners = await MyDeposit.methods.owner().call();
const balances = await MyDeposit.methods.getBalance().call();
It's now OK. I get the full field.

React Apex Chart Data, Image and API

How to modify series and options, i want to make chart type=treemap on react hooks like this
i have name, user and percent on api.
{
"data": [
{
"id": "1",
"name": "Pisces",
"user": "95",
"percent": "3.15%",
},
{
"id": "2",
"name": "Leo",
"user": "50",
"percent": "2.35%",
},
{
"id": "3",
"name": "Capricorn",
"user": "91",
"percent": "3.12%",
}
]
}
and source for apex https://apexcharts.com/docs/chart-types/treemap-chart/
import React, { useState,useEffect } from 'react';
import axios from 'axios';
import './App.css';
import Chart from 'react-apexcharts'
import icUser from './image/profile-user.png'
import icChart from './image/pie-chart.png'
const App =()=> {
const [dataUser,setDataUser]=useState([])
useEffect(() => {
axios.get("http://localhost:4000/data")
.then(response =>{
setDataUser(response.data)
}).catch(e => {
alert(e);
})
}, [])
const series = {.....}
const options = {.....}
return (
<div>
<Chart options={options} series={series} height={350} type="treemap"/>
</div>
)
}
export default App
In series you need to pass an array like this, Where x is the name, and y percentage. and In option you can modify the treemap chart like change height, type, plotOptions and more...
const App = () => {
const [dataUser, setDataUser] = useState([])
useEffect(() => {
axios.get("http://localhost:4000/data")
.then(response => {
setDataUser(response.data)
}).catch(e => {
alert(e);
})
}, [])
const seriesData = [];
const options = {}
dataUser.map((val) => {
seriesData.push(
{
x: val.name, //
y: val.percent //
}
);
});
const series = [{ data: seriesData }];
return (
<div>
<Chart options={options} series={series} height={350} type="treemap" />
</div>
)
}
export default App

Filter results from nested Arrays (small React application)

i'm trying to solve a challenge found on FrontEndMentor. In this excercise i have to map through a Data.Js file and show the content. After i'll have to filter those results according to various categories clicking on the respective buttons. Here is my App.js component:
function App() {
const [jobs, setJobs] = useState(Data)
const filterThis = (e, type)=>{
let categorySelected = e.target.value;
console.log(categorySelected);
if(type==="role"){
setJobs(Data.filter(job=> job.role===categorySelected))
} else if (type==="level"){
setJobs(Data.filter(job=> job.level===categorySelected))
}else if(type==="languages"){
???????
}
}
return (
<div className="App">
<header></header>
<div className="container">
{jobs.map(card=>{
return (
<Card
id={card.id}
company={card.company}
logo={card.logo}
isNew={card.new}
isFeatured={card.featured}
position={card.position}
role={card.role}
level={card.level}
postedAt={card.postedAt}
contract={card.contract}
location ={card.location}
languages={card.languages}
tools={card.tools}
filterThis={filterThis}
jobs={jobs}
/>
)
})}
</div>
</div>
);
}
export default App;
This is the Card.js component :
const Card =({id, company, logo, isNew, isFeatured, position, role, level, postedAt, contract, location, languages,tools, filterThis})=>{
return (
<div className="card">
<img src={logo}/>
<div className="main">
<div className="highlights">
<p className="company">{company}</p>
<p className="new">{isNew?"NEW!":null}</p>
<p className="featured">{isFeatured?"FEATURED":null}</p>
</div>
<h3>{position}</h3>
<div className="description">
<p>{postedAt}</p>
<p>{contract}</p>
<p>{location}</p>
</div>
</div>
<div className="buttons">
<Button filterThis ={filterThis} tools={tools} languages={languages} role={role} level={level}/>
</div>
</div>
)
}
export default Card;
The Button.js component:
import React, { useState } from 'react';
const Button = ({role, jobs, level, languages, tools, filterThis}) =>{
return (
<div>
<button value={role} onClick={(e)=>filterThis(e,"role")}>{role}</button>
<button value={level} onClick={(e)=>filterThis(e,"level")}>{level}</button>
{languages && languages.map(lang=>{
return (
<button value={lang} onClick={(e)=>filterThis(e,"languages", lang)}>{lang}</button>
)
})}
{tools && tools.map(tool=>{
return (
<button value={tool} onClick={(e)=>filterThis(e,"tools")}>{tool}</button>
)
})}
</div>
)
}
export default Button;
And the Data.js where i pull the data from:
{
"id": 1,
"company": "Photosnap",
"logo": "/images/photosnap.svg",
"new": true,
"featured": true,
"position": "Senior Frontend Developer",
"role": "Frontend",
"level": "Senior",
"postedAt": "1d ago",
"contract": "Full Time",
"location": "USA Only",
"languages": ["HTML", "CSS", "JavaScript"]
},
{
"id": 2,
"company": "Manage",
"logo": "./images/manage.svg",
"new": true,
"featured": true,
"position": "Fullstack Developer",
"role": "Fullstack",
"level": "Midweight",
"postedAt": "1d ago",
"contract": "Part Time",
"location": "Remote",
"languages": ["Python"],
"tools": ["React"]
},
{
"id": 3,
"company": "Account",
"logo": "./images/account.svg",
"new": true,
"featured": false,
"position": "Junior Frontend Developer",
"role": "Frontend",
"level": "Junior",
"postedAt": "2d ago",
"contract": "Part Time",
"location": "USA Only",
"languages": ["JavaScript"],
"tools": ["React", "Sass"]
},
Now i can correctly display on the front end the data and i can successfully filter the Role and the Level. The problem is trying to map those nested arrays "languages" and "tools". I can't find a way to map and filter them (while inside the Button component i mapped them without problems, but now filtering is the problem).
Hope i was clear, thank you for the help guys!
You could do it like this.
But anyway, you will need to add a clear button that will refresh your default object.
import React, { useState } from "react";
import "./App.css";
// import { filter } from "async";
import Data from "./data.js";
import Card from "./Card";
function App() {
const [jobs, setJobs] = useState(Data);
const filterThis = (e, type) => {
let categorySelected = e.target.value;
const filteredData = JSON.parse(JSON.stringify(Data));
if (type === "languages" || type === "tools") {
let x = filteredData.filter(item => {
if (typeof item[type] !== "undefined") {
if (item[type].includes(e.target.value)) {
return item;
}
}
});
setJobs(x);
} else {
setJobs(filteredData.filter(job => job[type] === categorySelected));
}
};

concat two json objects from different api by id in axios get and store

I have a question about how to add the second nested api query in axios. The second api query to get the json object based on the id from the first api array json. And then concat to global array in function Retrieve()?
first api url:
'/api/sets'
second api children:
'/api/sets/' + todo.id + '/tasks'
responce global json from first api url:
[
{
"id": 121,
"name": "list1",
"description": "description1"
},
{
"id": 9,
"name": "list2",
"description": "description2"
}
]
responce second json children from api by id first api:
[
{
"id": 1,
"name": "task1",
"description": "description task1"
},
{
"id": 2,
"name": "task2",
"description": "description task2"
}
]
and finally expected combined stored array json
[
{
"id": 121,
"name": "list1",
"description": "description1",
"task": [{
"id": 1,
"name": "task1",
"description": "description task1"
},
{
"id": 2,
"name": "task2",
"description": "description task2"
}
]
},
{
"id": 9,
"name": "list2",
"description": "description2",
"task": [{
"id": 10,
"name": "task1",
"description": "description task1"
},
{
"id": 11,
"name": "task2",
"description": "description task2"
}
]
}
]
code js:
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'mobx-react';
import TodoStore from './store';
const Root = (
<Provider TodoStore={TodoStore}>
<App />
</Provider>
);
ReactDOM.render(Root, document.getElementById('root'));
store.js
import React from 'react';
import { observable, action, configure, runInAction } from 'mobx';
import axios from 'axios';
configure({ enforceActions: 'observed' });
class TodoStore {
#observable todos = [];
#action Retrieve = () => {
axios
.get('/api/sets')
.then(response => {
let tempTodos = response.data;
runInAction(() => {
this.todos = tempTodos;
});
})
.catch(error => {
console.log(error);
});
};
}
const store = new TodoStore();
export default store;
If you API does not support GraphQL endpoint, then you should have to expand your Retrive() action and do extra XHR request for sets id to combine results from API endpoint 1 and 2.
#action Retrieve = () => {
axios
.get('/api/sets')
.then(response => {
let tempTodos = response.data;
let todosWithTasks = tempTodos.map(todo => {
let tasks = null;
axios.get('/api/sets/' + todo.id + '/tasks')
.then(response2 => {
tasks = response2.data;
}).catch(error => {
console.log(error);
});
todo.task = tasks;
return todo;
});
// `todosWithTasks` is joined API1 and API2
})
.catch(error => {
console.log(error);
});
};
Thanks it works, all api is joined, now I have another little problem. If set #observable.ref todos = []; or #observable.shallow todos = []; in console log key task exitst with array of objects, but when I set #observable todos = []; key task no exist.
console.log
(2) [{…}, {…}]
0:
description: "false"
id: 121
name: "list1"
task: Array(2)
0: {id: 10, name: "task1", description: "description task1", state: false, position: 1}
1: {id: 11, name: "task2", description: "description task2", state: true position: 2}
length: 2
__proto__: Array(0)
__proto__: Object
1:
description: "false"
id: 9
name: "list2"
task: Array(2)
0: {id: 3, name: "task1", description: "description task1", state: false, position: 3}
1: {id: 7, name: "task2", description: "description task2", state: false, position: 5}
length: 2
__proto__: Array(0)
__proto__: Object
length: 2
__proto__: Array(0)
and if try map key task
index.module.js:206 Uncaught TypeError: Cannot read property 'map' of undefined
at eval (TodoItem.jsx:17)
at eval (index.module.js:220)
at eval (index.module.js:198)
at trackDerivedFunction (mobx.module.js:1212)
at Reaction.track (mobx.module.js:1752)
at useObserver (index.module.js:196)
at wrappedComponent (index.module.js:220)
at renderWithHooks (react-dom.development.js:12938)
at updateFunctionComponent (react-dom.development.js:14627)
at updateSimpleMemoComponent (react-dom.development.js:14573)
react-dom.development.js:17117 The above error occurred in the <wrappedComponent> component:
in wrappedComponent (created by n)
in n (created by inject-with-TodoStore(Object))
in inject-with-TodoStore(Object) (created by App)
in div (created by App)
in App (created by n)
in n (created by inject-with-TodoStore(App))
in inject-with-TodoStore(App)
in e
code index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import { Provider } from 'mobx-react';
import TodoStore from './TodoStore';
import registerServiceWorker from './registerServiceWorker';
const Root = (
<Provider TodoStore={TodoStore}>
<App />
</Provider>
);
ReactDOM.render(Root, document.getElementById('root'));
registerServiceWorker();
TodoStore.js
import React from 'react';
import {observable, action, computed, configure, runInAction} from 'mobx';
import axios from 'axios';
axios.defaults.baseURL = 'api';
configure({ enforceActions: 'observed' });
class TodoStore {
#observable.shallow todos = [];
#action Retrieve = () => {
axios
.get('/sets')
.then(response => {
let tempTodos = response.data;
let todosWithTasks = tempTodos.map(todo => {
let tasks = null;
axios
.get('/sets/' + todo.id + '/tasks')
.then(response2 => {
todo.task = response2.data;
})
.catch(error => {
console.log(error);
});
return todo;
});
runInAction(() => {
this.todos = todosWithTasks;
});
})
.catch(error => {
console.log(error);
});
};
}
const store = new TodoStore();
export default store;
app.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TodoItem from './TodoItem';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
#inject('TodoStore')
#observer
class App extends Component {
render() {
const TodoStore = this.props.TodoStore;
console.log(toJS(TodoStore.todos));
return (
<div className="App">
{TodoStore.todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</div>
);
}
async componentDidMount() {
this.props.TodoStore.Retrieve();
}
}
TodoItem.wrappedComponent.propTypes = {
todo: PropTypes.object.isRequired,
TodoStore: PropTypes.object.isRequired
};
export default App;
todoitem
import React from 'react';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';
import TodoItemTask from './TodoItemtask';
const TodoItem = inject('TodoStore')(
observer(props => {
const TodoStore = props.TodoStore;
return (
<>
<div key={props.todo.id} className="todo-item">
<span>{props.todo.id}</span>
<h5>{props.todo.name}</h5>
<p>{props.todo.description}</p>
{props.todo.task.map((item, index) => (
<TodoItemTask key={index + item.id} item={item} />
))}
</div>
</>
);
})
);
TodoItem.wrappedComponent.propTypes = {
todo: PropTypes.object.isRequired,
TodoStore: PropTypes.object.isRequired
};
export default TodoItem;
TodoItemTask.js
import React from 'react';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';
const TodoItemTask = inject('TodoStore')(
observer(props => {
const TodoStore = props.TodoStore;
return (
<>
<div key={props.item.id} className="todo-item">
<span>{props.index}</span>
<p>{props.item.name}</p>
<p>{props.item.description}</p>
</div>
</>
);
})
);
TodoItemTask.wrappedComponent.propTypes = {
item: PropTypes.object.isRequired,
TodoStore: PropTypes.object.isRequired
};
export default TodoItemTask;
no errors and render all data if set static data
#observable todos = [
{
"id": 121,
"name": "list1",
"description": "description1",
"task": [{
"id": 1,
"name": "task1",
"description": "description task1"
},
{
"id": 2,
"name": "task2",
"description": "description task2"
}
]
},
{
"id": 9,
"name": "list2",
"description": "description2",
"task": [{
"id": 10,
"name": "task1",
"description": "description task1"
},
{
"id": 11,
"name": "task2",
"description": "description task2"
}
]
}
];
Actually, this is not a problem with mobx, I found that two api url json are incorrectly connected in this function.
In console.log(todosWithTasks) it looks right, but this console.log (JSON.stringify(todosWithTasks)) not.
this is actual code
import React from 'react';
import {observable, action, computed, configure, runInAction} from 'mobx';
import axios from 'axios';
axios.defaults.baseURL = 'api';
configure({ enforceActions: 'observed' });
class TodoStore {
#observable todos = [];
#action async Retrieve = () => {
this.isLoading = true;
await axios
.get('/sets')
.then(async response => {
let tempTodos = response.data;
tempTodos.forEach(todo => (todo.task = []));
let todosWithTasks = tempTodos.map(todo => {
axios
.get('/sets/' + todo.id + '/tasks')
.then(response2 => {
todo.task = response2.data;
return todo;
})
.catch(error => {
console.log(error);
});
return todo;
});
runInAction(() => {
console.log(todosWithTasks);
console.log(JSON.stringify(todosWithTasks));
this.todos = todosWithTasks;
});
})
.catch(error => {
console.log(error);
});
};
}
const store = new TodoStore();
export default store;
output from console.log(JSON.stringify(todosWithTasks))
[{"id":1,"name":"list1","description":"description1","task":[]}]
output from console.log(todosWithTasks) looks fine
(1) [{…}]
0:
description: "description1"
id: 1
name: "list1"
task: Array(1)
0: {id: 1, name: "task1", description: "description task1"}
length: 1
__proto__: Array(0)
__proto__: Object
length: 1
__proto__: Array(0)
therefore, it does not render in the map function, because the key task is empty.
If the modified merged json file localy, in axios it's everything ok. In console.log (JSON.stringify (todosWithTasks)) everything fine.
#action Retrieve() {
axios
.get('localhost:3000/src/data.json')
.then(response => {
let tempTodos = response.data;
tempTodos.forEach(todo => (todo.editing = false));
runInAction(() => {
this.todos = tempTodos;
console.log(JSON.stringify(tempTodos));
});
})
.catch(error => {
console.log(error);
});
}

Getting "No applicable renderer found" when using React and JSONSchema Form

I'm learning React and decided to check out JSON Forms ( https://jsonforms.io/docs/tutorial ).
I can get the seed app from https://github.com/eclipsesource/jsonforms-react-seed running, and I also experimented with moving all the form-related stuff into its own component, instead of putting it all in index.js. That works great in the seed app.
Then I decided to try to set up the demo form from the playground schema ( https://mozilla-services.github.io/react-jsonschema-form/ ) in the seed app, just to make sure I knew how to change a form.
This is where the wheels came off. Instead of a form, I get "No applicable renderer found."
I copied the three inputs in the playground ( schema, UISchema, and formData ). Below is the code from the separate component, with the schema, uischema, and data taken directly from the playground data jsonschema provides:
import { JsonForms } from '#jsonforms/react';
import React from 'react';
import { combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';
import { Actions, jsonformsReducer } from '#jsonforms/core';
import { materialFields, materialRenderers } from '#jsonforms/material-renderers';
const data = {
firstName: "Chuck",
lastName: "Norris",
age: 75,
bio: "Roundhouse kicking asses since 1940",
password: "noneed"
};
const schema = {
"title": "A registration form",
"description": "A simple form example.",
"type": "object",
"required": [
"firstName",
"lastName"
],
"properties": {
"firstName": {
"type": "string",
"title": "First name"
},
"lastName": {
"type": "string",
"title": "Last name"
},
"age": {
"type": "integer",
"title": "Age"
},
"bio": {
"type": "string",
"title": "Bio"
},
"password": {
"type": "string",
"title": "Password",
"minLength": 3
},
"telephone": {
"type": "string",
"title": "Telephone",
"minLength": 10
}
}
};
const uischema = {
"firstName": {
"ui:autofocus": true,
"ui:emptyValue": ""
},
"lastName": {
"ui:autofocus": true,
"ui:emptyValue": ""
},
"age": {
"ui:widget": "updown",
"ui:title": "Age of person",
"ui:description": "(earthian year)"
},
"bio": {
"ui:widget": "textarea"
},
"password": {
"ui:widget": "password",
"ui:help": "Hint: Make it strong!"
},
"telephone": {
"ui:options": {
"inputType": "tel"
}
}
};
const store = createStore(
combineReducers({ jsonforms: jsonformsReducer() }),
{
jsonforms: {
fields: materialFields,
renderers: materialRenderers
},
}
);
store.dispatch(Actions.init(data, schema, uischema));
function SampleForm() {
return (
<div>
<Provider store={store}>
<JsonForms />
</Provider>
</div>);
}
export default SampleForm;
index.js looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<App />,
document.getElementById('root')
);
registerServiceWorker();
and finally, the app itself, App.js, looks like this:
import React from 'react';
import './App.css';
import SampleForm from './sampleform';
const styles = {
container: {
padding: '1em'
},
title: {
textAlign: 'center',
padding: '0.25em'
},
dataContent: {
display: 'flex',
justifyContent: 'center',
borderRadius: '0.25em',
backgroundColor: '#cecece',
},
demoform: {
margin: 'auto'
}
};
const App = () => (
<div>
<SampleForm/>
</div>
);
export default App;
<JsonForms
schema={schema}
uischema={Generate.uiSchema(schema)}
data={data}
renderers={materialRenderers}
/>
https://github.com/eclipsesource/jsonforms/issues/923#issuecomment-374936319

Resources