Implementing Uppy.io StatusBar in react - reactjs

I am trying to implement an Uppy.io statusbar upload as a react component. I tried using the wrapper but it does not work. If I use Dashboard or DragDrop then it does. Are there any tutorials or examples I could refer to ? My code looks like:
const UppyUpload = ({ uploadPayload }) => {
const uppy = useUppy(() => {
return new Uppy({
meta: { CaseId: '29670', CustomerId: '107', projectTitle: 'Trial' },
restrictions: { maxNumberOfFiles: 1 },
autoProceed: false,
})
.use(XHRUpload, {
endpoint: 'api/FormController/UploadVideo',
formData: true,
fieldName: 'Files',
})
.on('complete', (result) => {
const url = result.successful[0].uploadURL;
store.dispatch({
type: 'SET_USER_AVATAR_URL',
payload: { url },
});
});
});
return (
<div>
<StatusBar
uppy={uppy}
hideAfterFinish={false}
showProgressDetails
/>
</div>
);
};

Related

The ContentLayer library dosen't return "code" property for MDXComponent

I'm using ContentLayer library for import MDX content in my blog.
I've read a several opensource code and I following them, but in my case I don't have "code" property in my "body" object.
while I cloend other opensource project and they works correctly and I saw they have "code" property in their "body" object.
this is my [slug].tsx:
import BlogLayout from '#layouts/blog';
import { useMDXComponent } from 'next-contentlayer/hooks';
import { allBlogs } from '../../.contentlayer/generated';
import type { Blog } from '../../.contentlayer/generated';
type BlogProps = {
blog: Blog;
};
export default function Blog({ blog }: BlogProps) {
console.log(blog.body.code);
const Component = useMDXComponent(blog.body.code);
return (
<BlogLayout blog={blog}>
<Component />
</BlogLayout>
);
}
export const getStaticPaths = async () => {
return {
paths: allBlogs.map(p => ({ params: { slug: p.slug } })),
fallback: false,
};
};
export const getStaticProps = async ({ params }) => {
const blog = allBlogs.find(p => p.slug === params.slug);
return {
props: {
blog,
},
};
};
and this is my contentLayer configuration:
import { defineDocumentType, makeSource } from 'contentlayer/source-files';
import mdxOptions from './config/mdx';
import readingTime from 'reading-time';
export const Blog = defineDocumentType(() => ({
name: 'Blog',
bodyType: 'mdx',
filePathPattern: `blogs/**/*.mdx`,
fields: {
title: { type: 'string', required: true },
publishedAt: { type: 'string', required: true },
description: { type: 'string', required: true },
cover: { type: 'string' },
tag: { type: 'string' },
},
computedFields: {
readingTime: {
type: 'json',
resolve: doc => readingTime(doc.body.raw),
},
slug: {
type: 'string',
resolve: doc => doc._raw.sourceFileName.replace(/\.mdx$/, ''),
},
},
}));
export default makeSource({
contentDirPath: '_posts',
documentTypes: [Blog],
mdx: mdxOptions,
});
In my case "body" object has these objects: { _raw , html }
I don't know what's the problem and why I don't have "code" property in my "body" object
I appreciate all feedback from you.
I found in version 0.1.0 release contains two (2) breaking changes. that one of them is:
💥 [Breaking] bodyType will be replaced by contentType.

Updating Graph on Interval on React

I am getting data from my database to display it on the graph. Currently, I will have to refresh the page for the graph to update. I would like to refresh the graph in x interval as my data will be inserted at x interval. Am using ant design for the graph plotting. I am using a 'home' to display my graph and another class for my data fetching.
Home.js
export class Home extends Component {
static displayName = Home.name;
render () {
return (
<div>
<h1>Dashboard</h1>
<h2>
<div className="site-card-wrapper">
Graph1
<Graph />}
</div>
</h2>
</div>
);
}
}
Temp.js
const TempGraph = () => {
const [data, setData] = useState([]);
useEffect(() => {
asyncFetch();
}, []);
const asyncFetch = () => {
fetch('link')
.then((response) => response.json())
.then((json) => setDatajson))
.catch((error) => {
console.log('fetch data failed', error);
});
};
const config = {
data,
xField: 'time',
yField: 'value',
seriesField:'location',
xAxis: {
title: {
text: 'Hours',
}
},
yAxis:{
title:{
text: 'Temperature in °',
}
},
meta: {
time: {
alias: 'hours',
},
value: {
alias: 'temperature',
max: 50,
},
},
};
return <Line {...config} />;
}
export default TempGraph;
You could just add a setInterval in your useEffect to grab the data and update them again. Don't forgot to clear the interval on return:
useEffect(() => {
const interval = setInterval(() => asyncFetch(), 5000)
return () => clearInterval(interval)
}, []}
This example triggers every 5000ms, change the value according to your needs.

calling setState from onClick JavaScript function not working

I am trying to create a button that will make visible a form to edit any contact on my list. However, when I press the button, nothing happens.
I have the initial state set to
this.state = {
contacts: [],
showEditWindow: false,
EditContactId: ''
};
I added a function:
editContact = (id) => {
this.setState({
showEditWindow: true, EditContactId: {id}
});
};
and a column:
{
title: "",
key: "action",
render: (record) => (
<button onClick={() => this.editContact(record.id)}
>
Edit
</button>
)
},
I imported EditContactModal and call it as
<EditContactModal reloadContacts={this.reloadContacts}
showEditWindow={this.state.showEditWindow}
EditContactId={this.state.EditContactId}/>
If I manually set this.state to showEditWindow:true, the window appears; however, either this.editContact(id) is not being called or it is not changing the state.
Calling this.deleteContact(id) works fine, as does setState in loadContacts() and reloadContacts()
What I am doing wrong?
Below are the full components.
Contacts.jsx
import { Table, message, Popconfirm } from "antd";
import React from "react";
import AddContactModal from "./AddContactModal";
import EditContactModal from "./EditContactModal";
class Contacts extends React.Component {
constructor(props) {
super(props);
this.state = {
contacts: [],
showEditWindow: false,
EditContactId: ''
};
this.editContact = this.editContact.bind(this);
};
columns = [
{
title: "First Name",
dataIndex: "firstname",
key: "firstname"
},
{
title: "Last Name",
dataIndex: "lastname",
key: "lastname"
},{
title: "Hebrew Name",
dataIndex: "hebrewname",
key: "hebrewname"
},{
title: "Kohen / Levi / Yisroel",
dataIndex: "kohenleviyisroel",
key: "kohenleviyisroel"
},{
title: "Frequent",
dataIndex: "frequent",
key: "frequent",
},{
title: "Do Not Bill",
dataIndex: "donotbill",
key: "donotbill"
},
{
title: "",
key: "action",
render: (record) => (
<button onClick={() => this.editContact(record.id)}
>
Edit
</button>
)
},
{
title: "",
key: "action",
render: (_text, record) => (
<Popconfirm
title="Are you sure you want to delete this contact?"
onConfirm={() => this.deleteContact(record.id)}
okText="Yes"
cancelText="No"
>
<a type="danger">
Delete{" "}
</a>
</Popconfirm>
),
},
];
componentDidMount = () => {
this.loadContacts();
}
loadContacts = () => {
const url = "http://localhost:3000/contacts";
fetch(url)
.then((data) => {
if (data.ok) {
return data.json();
}
throw new Error("Network error.");
})
.then((data) => {
data.forEach((contact) => {
const newEl = {
key: contact.id,
id: contact.id,
firstname: contact.firstname,
lastname: contact.lastname,
hebrewname: contact.hebrewname,
kohenleviyisroel: contact.kohenleviyisroel,
frequent: contact.frequent.toString(),
donotbill: contact.donotbill.toString(),
};
this.setState((prevState) => ({
contacts: [...prevState.contacts, newEl],
}));
});
})
.catch((err) => message.error("Error: " + err));
};
reloadContacts = () => {
this.setState({ contacts: [] });
this.loadContacts();
};
deleteContact = (id) => {
const url = `http://localhost:3000/contacts/${id}`;
fetch(url, {
method: "delete",
})
.then((data) => {
if (data.ok) {
this.reloadContacts();
return data.json();
}
throw new Error("Network error.");
})
.catch((err) => message.error("Error: " + err));
};
editContact = (id) => {
this.setState({
showEditWindow: true, EditContactId: {id}
});
};
render = () => {
return (
<>
<Table
className="table-striped-rows"
dataSource={this.state.contacts}
columns={this.columns}
pagination={{ pageSize: this.pageSize }}
/>
<AddContactModal reloadContacts={this.reloadContacts} />
<EditContactModal reloadContacts={this.reloadContacts}
showEditWindow={this.state.showEditWindow}
EditContactId={this.state.EditContactId}/>
</>
);
}
}
export default Contacts;
EditContactModal.jsx
import { Button, Form, Input, Modal, Select } from "antd";
import React from "react";
import ContactForm from './ContactForm';
const { Option } = Select;
class EditContactModal extends React.Component {
formRef = React.createRef();
state = {
visible: this.props.showEditWindow,
};
onFinish = (values) => {
const url = `http://localhost:3000/contacts/${this.props.EditContactId}`;
fetch(url, {
method: "put",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(values),
})
.then((data) => {
if(data.ok) {
this.handleCancel();
return data.json();
}
throw new Error("Network error.");
})
.then(() => {
this.props.reloadContacts();
})
.catch((err) => console.error("Error: " + err))
};
showModal = () => {
this.setState({
visible: true,
});
};
handleCancel = () => {
this.setState({
visible: false,
});
};
render() {
return (
<>
{/*<Button type="primary" onClick={this.showModal}>
Create New +
</Button>*/}
<Modal
title="Edit Contact"
visible={this.state.visible}
onCancel={this.handleCancel}
footer={null}
>
<ContactForm />
</Modal>
</>
);
}
}
export default EditContactModal;
if your aim is to perform an update to the state object, you must not pass mutable data, but copy it instead into a new object.
this will allow the state changes to be picked up.
so, prefer setState({ ...state, ...someObject }) over setState(someObject).

Zustand state does not re-render component or passes data correctly to then display filtered items

I'm using Zustand to store state, everything is working fine apart from this. When i click on the Song Buttons i want that to filter from the list.
Currently on fresh load it displays 3 songs. When clicking the button it should filter (and it does for first instance) but as soon as i click another button to filter again then nothing happens.
So if i chose / click Song 1 and Song 2 it should only show these songs.
I think the logic i wrote for that is correct but i must be doing something wrong with re-rendering.
Sorry i know people like to upload example here but i always find it hard with React files, so for this case I'm using https://codesandbox.io/s/damp-waterfall-e63mn?file=/src/App.js
Full code:
import { useEffect, useState } from 'react'
import create from 'zustand'
import { albums } from './albums'
export default function Home() {
const {
getFetchedData,
setFetchedData,
getAttrData,
setAttrData,
getAlbumData,
getButtonFilter,
setButtonFilter,
setAlbumData,
testState,
} = stateFetchData()
useEffect(() => {
if (getFetchedData) setAttrData(getFetchedData.feed.entry)
}, [getFetchedData, setAttrData])
useEffect(() => {
setAlbumData(getButtonFilter)
}, [getButtonFilter, setAlbumData])
// useEffect(() => {
// console.log('testState', testState)
// console.log('getAlbumData', getAlbumData)
// }, [getAlbumData, testState])
useEffect(() => {
setFetchedData()
}, [setFetchedData])
return (
<div>
<div>Filter to Show: {JSON.stringify(getButtonFilter)}</div>
<div>
{getAttrData.map((props, idx) => {
return (
<FilterButton
key={idx}
attr={props}
getDataProp={getButtonFilter}
setDataProp={setButtonFilter}
/>
)
})}
</div>
<div>
{getAlbumData?.feed?.entry?.map((props, idx) => {
return (
<div key={idx}>
<h1>{props.title.label}</h1>
</div>
)
})}
</div>
</div>
)
}
const FilterButton = ({ attr, getDataProp, setDataProp }) => {
const [filter, setFilter] = useState(false)
const filterAlbums = async (e) => {
const currentTarget = e.currentTarget.innerHTML
setFilter(!filter)
if (!filter) setDataProp([...getDataProp, currentTarget])
else setDataProp(getDataProp.filter((str) => str !== currentTarget))
}
return <button onClick={filterAlbums}>{attr.album}</button>
}
const stateFetchData = create((set) => ({
getFetchedData: albums,
setFetchedData: async () => {
set((state) => ({ ...state, getAlbumData: state.getFetchedData }))
},
getAttrData: [],
setAttrData: (data) => {
const tempArr = []
for (const iterator of data) {
tempArr.push({ album: iterator.category.attributes.label, status: false })
}
set((state) => ({ ...state, getAttrData: tempArr }))
},
getButtonFilter: [],
setButtonFilter: (data) => set((state) => ({ ...state, getButtonFilter: data })),
testState: {
feed: { entry: [] },
},
getAlbumData: [],
setAlbumData: (data) => {
set((state) => {
console.log('🚀 ~ file: index.js ~ line 107 ~ state', state)
const filter = state.getAlbumData.feed?.entry.filter((item) =>
data.includes(item.category.attributes.label),
)
return {
...state,
getAlbumData: {
...state.getAlbumData,
feed: {
...state.getAlbumData.feed,
entry: filter,
},
},
}
})
},
}))
Sample data:
export const albums = {
feed: {
entry: [
{ title: { label: 'Song 1' }, category: { attributes: { label: 'Song 1' } } },
{ title: { label: 'Song 2' }, category: { attributes: { label: 'Song 2' } } },
{ title: { label: 'Song 3' }, category: { attributes: { label: 'Song 3' } } },
],
},
}

Undefined values React

I'm trying to achieve making a suspend user button via updating the values of the user the status to Suspended, but the problem is the status is defined but other values are undefined did I do something wrong or is there any way to update the values to make the other variable like a name not required?
This is what I mean:
This is my code:
const User = (props) => (
<>
<DropdownButton id="dropdown-basic-button" title="Action">
<Dropdown.Item>
<a
href="user"
onClick={() => {
props.onSubmit(props.user[0]);
}}
>
<i className="fas fa-trash"></i> Suspend
</a>
</Dropdown.Item>
</DropdownButton>
</>
);
export default class Users extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.state = { users: [] };
}
componentDidMount() {
axios
.get("http://localhost:5000/users/")
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
onSubmit(id) {
const user = {
name: this.state.name,
password: this.state.password,
email: this.state.email,
storeName: this.state.storeName,
storeUrl: this.state.storeUrl,
date: this.state.date,
status: "Suspended",
};
console.log(user);
axios
.post("http://localhost:5000/users/update/" + id, user)
.then((res) => console.log(res.data));
}
userList(currentuser) {
return (
<User
user={currentuser}
key={currentuser[0]}
onSubmit={this.onSubmit}
/>
);
}
render() {
const columns = [
{
name: "_id",
options: {
display: false,
},
},
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
},
},
{
name: "Action",
options: {
customBodyRender: (value, tableMeta, updateValue) => {
return <>{this.userList(tableMeta.rowData)}</>;
},
},
},
];
const { users } = this.state;
return (
<>
<MUIDataTable data={users} columns={columns} />
</>
);
}
}
You didn't define nor set the User's individual attributes' values in the state! So, no wonder they show up as undefined, when you try to read them...
The simplest solution would be:
onSubmit(id) {
//let user = this.state.users.find(user => user.id === id); // find by id
let user = this.state.users[id]; // find by index
if (user) {
user.status = 'Suspended';
console.log(user);
axios
.post("http://localhost:5000/users/update/" + id, user)
.then((res) => console.log(res.data));
}
}

Resources