Filepond extracting base64 react js - javascript

Trying to get a base64 from image upload and send it to the server. with other values, i can get the value of the hidden inputs. Api is configured to take 2 files at a time, so i cant process the uploads separately at this point
Having trouble mapping the 'data' from the upload image's value i have tried simple mapping methods but still failing.
My code below
import React, { Component } from 'react';
import {connect} from 'react-redux'
import {Button} from 'antd'
import IntlMessages from '../utility/intlMessages';
import authActions from '../../redux/auth/actions'
import { apiUrl } from '../../config';
import { FilePond, registerPlugin } from 'react-filepond';
import 'filepond/dist/filepond.min.css';
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import FilePondPluginImageExifOrientation from 'filepond-plugin-image-exif-orientation';
import FilePondPluginImageTransform from 'filepond-plugin-image-transform';
import FilePondPluginFileEncode from 'filepond-plugin-file-encode';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css';
registerPlugin(FilePondPluginImagePreview,
FilePondPluginImageExifOrientation, FilePondPluginImageTransform, FilePondPluginFileEncode);
const { kycUploadDocs } = authActions;
class FilePondCompnent extends Component {
constructor(props) {
super(props);
this.state = {
files: [],
base64files: []
};
}
handleFilesUpdate() {
let munei = document.querySelector('.filepond--file-wrapper');
if(this.pond.getFiles().length === 2) {
const input = munei.querySelectorAll('input[type="hidden"]')[0]
console.log(input.value)
base64map => {
this.setState({
base64files: input.value.map(req => req.data)
});
}
}
}
handleInit() {
console.log("FilePond instance has initialised", this.pond);
}
render() {
return (
<div className="munei">
{/* Pass FilePond properties as attributes */}
<FilePond
ref={ref => (this.pond = ref)}
files={this.state.files}
allowMultiple={true}
maxFiles={2}
instantUpload={false}
allowRevert={false}
allowFileEncode={true}
// oninit={() => this.handleInit()}
onupdatefiles={fileItems => {
// Set currently active file objects to this.state
this.setState({
files: fileItems.map(fileItem => fileItem.file)
});
this.handleFilesUpdate()
}}
/>
</div>
);
}
}
export default connect((state, ownProps) => ({
// isLoading: state.App.get('isLoading'),
// balances: state.Funds.get(ownProps.fund+'_balances'),
}),
{ kycUploadDocs }
)(FilePondCompnent);

The latest version of the file encode plugin adds two methods to the file items. getFileEncodeBase64String and getFileEncodeDataURL. Those should help achieve what you're trying to do without actually having to read the hidden file input elements.
See docs for further info: https://pqina.nl/filepond/docs/patterns/plugins/file-encode/

Related

Using ReactDOM.render in class

I have a very unique issue where I need to render components with different ids on a site, and cannot render all the content under one ID.
I have been able to collect a JSON array through a GET request and have been able to get a for each loop for each array, however I just need to render that particular data with an ID passed from the array.
I have tried to use ReactDom.render in a class but I cannot find how this can be done & and I have current set document.getElementById('modules') to one particular div to begin with to see if that would render, but having no luck.
Any help would be appreciated.
Index.js
`
import { ColorModeScript } from '#chakra-ui/react';
import React, { StrictMode } from 'react';
import { Component } from 'react';
import { ChakraProvider } from "#chakra-ui/react";
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import * as serviceWorker from './serviceWorker';
import Theme from "./theme";
import Page from "./structure/Page";
import axios from "axios";
class Index extends Component {
constructor(props) {
super(props);
this.state = {
modules: [],
};
}
componentDidMount() {
var currentPath = window.location.pathname;
if (currentPath === '/') {
currentPath = '/home';
}
axios
.get("/lite/modules" + currentPath)
.then((response) => {
const data = response.data;
this.setState({ modules: data });
Object.entries(data).forEach(data1 => {
var ModuleData = data1[1];
this.renderModule(ModuleData);
});
})
.catch((error) => {
console.log(error);
});
}
renderModule(ModuleData){
console.log(ModuleData);
var divID = "module" + ModuleData.type;
ReactDOM.render(
<h1>demo</h1>,
document.getElementById('modules')
);
}
render() {
return (
<ChakraProvider theme={Theme}>
<Page modules={this.state.modules} />
</ChakraProvider>
);
}
}
export default Index;
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorker.unregister();
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:
reportWebVitals();
`
Render multiple react components with different IDs.
I think you need to add this to your constructor:
this.renderModule = this.renderModule.bind(this)
if you have another server for the DB:
you need to do that when using axios:
axios.get(`${process.env.REACT_APP_SERVER_URL || '**LOCAL_SERVER_URL**'}/...`)

How we can share state object to another react file

in the first react file i called an api to get some data and save it in this.state.Data
import React, { Component } from "react";
import axios from "axios";
import Layout from "./Layout";
class Db extends Component {
constructor() {
super();
this.state = {
Data: [],
};
}
componentDidMount() {
axios.get(`https://breakingbadapi.com/api/characters`).then((res) => {
const data = res.data;
this.setState({ Data: data });
});
}
render() {
return <h1>DB working</h1>;
}
}
export default Db;
in the another react file i need to get this.props.Data from Db.js file but i dont know how to get it
import React, { Component } from "react";
import Db from "./Db";
class Filler extends Component {
constructor() {
super();
}
render() {
return <div></div>;
}
}
export default Filler;
for small projects you can use React ContextApi to save states in global level and use it inside components you want.
for big projects you can use state management libraries like Redux. it's too much for small projects.

How do I make a client-side only component for GatsbyJS?

How do I create a component for Gatsby that will load on the client-side, not at build time?
I created this one and it renders with gatsby develop but not with the rendered server-side rendering
import React from 'react';
import axios from 'axios';
import adapter from 'axios-jsonp';
export default class Reputation extends React.Component<{}, { reputation?: number }> {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
const response = await axios({
url: 'https://api.stackexchange.com/2.2/users/23528?&site=stackoverflow',
adapter
});
if (response.status === 200) {
const userDetails = response.data.items[0];
const reputation = userDetails.reputation;
this.setState({
reputation
});
}
}
render() {
return <span>{ this.state.reputation?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") }</span>
}
}
If you don't want the component to be bundled in the main js file at build time, use loadable-components
Install loadable-components and use it as a wrapper for a component that wants to use a client-side only package. docs
import React, { Component } from "react";
import Loadable from "#loadable/component";
const LoadableReputation = Loadable(() =>
import("../components/Reputation")
);
const Parent = () => {
return (
<div>
<LoadableReputation />
</div>
);
};
export default Parent;
before render this component, make sure you have a window, to detect if there is a window object. I would write a hook for that:
function hasWindow() {
const [isWindow, setIsWindow] = React.useState(false);
React.useEffect(() => {
setIsWindow(true);
return ()=> setIsWindow(false);
}, []);
return isWindow;
}
In the parent component check if there is a window object:
function Parent(){
const isWindow = hasWindow();
if(isWindow){
return <Reputation />;
}
return null;
}

How to load data in Meteor App using React?

Intro:
I'm newbie in meteor, I have read the documentation and questions here about this issue but the doubt still persist. My main problem is that I cant load data of my MongoDb in client side (what methods to use to load data).
Example:
I have a project that has the following folder structure:
image
In my collections (People.js) I have this:
import { Mongo } from 'meteor/mongo';
export const People = new Mongo.Collection('people');
In the server folder ( main.js ). PS: I can't change this file.
import { People } from '../collections/people';
Meteor.startup(() => {
const TEST_DATA = [
{
something: 'This is a simple example',
}, ... ]
TEST_DATA.forEach(test => People.insert(test));
}
In UI folder (app.jsx)
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { Meteor } from 'meteor/meteor';
import {People} from '../collections/people';
export class App extends Component {
render() {
return (
<div>
<h3>Teste </h3>
{ console.log(this.users) }
{ console.log(People.find({}).fetch()) }
{ console.log(Meteor.subscribe('people')) }
</div>
);
}
}
export default withTracker(() => {
return {
users: People.find({}).fetch(),
};
})(App);
cliente folder (main.jsx):
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { App } from '../ui/App';
Meteor.startup(() => {
render(<App />, document.getElementById('app'));
});
Debug:
I inspected the database and it's populated. The first console.log show undefined , the second an array of length:0, the third an object {stop: ƒ, ready: ƒ, subscriptionId: "mJQHdGxka4xTCX7FZ"} (I think it's returning this because I'm not using publish () on the server to populate the database)
What method should I use to obtain this data?
Change app.jsx to
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import { Meteor } from 'meteor/meteor';
import {People} from '../collections/people';
export class App extends Component {
render() {
console.log(this.props.users)
return (
<div>
<h3>Teste </h3>
{ this.props.users.map((user) => { return (<div>user.something</div>) }) }
</div>
);
}
}
export default withTracker(() => {
Meteor.subscribe('people');
return {
users: People.find({}).fetch(),
};
})(App);
I've modified the code a little further in the direction that I would assume you'd want it to go. The core change is it use this.props.users. That's where the properties in React components can be found, and where they are places by the function returned by withTracker.
This all assumes that you are still using autopublish (as meteor does in new projects until you remove it). If you have already removed that package, then you need to add
Meteor.publish('people', () => {
return People.find();
});
in your server code.

Search React/Redux.

I am really new to Reac.js/Redux.js and javascript in general. I am trying to learn a new language by actually doing it. I am trying to build a simple app that lets you search for the product. Eventually, I will create additional features that will allow a user to add and to remove the items form the list of products.
So far, I have built two containers: ListOfProd and Search. Everything works except I can’t figure out how filter the list of products based on the search criteria entered by a user. Where would be the best place to implement filter? and What would be the best way to filter the array of objects based on the search criteria? Please let me know how I can improve my code!
Container Search.js
import React, {Component} from 'react';
import {bindActionCreator} from 'redux';
import {connect} from 'react-redux';
//import scroll for search
//import Scroll from './components/Search/Scroll';
import SearchBox from '../components/Search/SearchBox';
//import action for search
import {setSearchField} from '../actions/actionSearch';
//list of prod
import ListOfProd from './ListOfProd';
const mapStateToProps = state =>{
return{
product: state.product,
searchField: state.searchField
}
}
const mapDispatchToProps = (dispatch) => {
return{
onSearchChange: (event) => dispatch(setSearchField(event.target.value))
}
}
class Search extends React.Component{
render(){
const {searchField, onSearchChange} = this.props;
// const filterProduct = this.props.product.filter(product =>{
// return product.prod.includes(searchField);
// })
return(
<div className = 'tc'>
<SearchBox searchChange={onSearchChange}></SearchBox>
<ListOfProd></ListOfProd>
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Search);
Container ListOfProd.js
// import Component
// hook it up to data store
import React, {Component} from 'react';
import {bindActionCreator} from 'redux';
import {connect} from 'react-redux';
//import Search from 'Search';
class ListOfProd extends React.Component {
createListItems(){
console.log(this.props.product);
return this.props.product.map((product, i) => {
console.log(this.props.product.prod);
console.log(this.props.searchField);
return(
<li key={i}>{product.prod} {product.price}</li>
)
});
}
render(){
return(
<ul>
{this.createListItems()}
</ul>
)
}
}
const mapStateToProps = state =>{
return{
product: state.searchProd.product,
searchField: state.searchProd.searchField
}
}
export default connect(mapStateToProps)(ListOfProd);
Actions
import {CHANGE_SEARCH_FIELD} from '../constants/constants';
export const setSearchField = (text) => ({
type: CHANGE_SEARCH_FIELD,
payload: text
})
Reducer ReducerSearch.js
import {CHANGE_SEARCH_FIELD} from '../constants/constants';
import React from 'react';
const initialState = {
searchField: '',
product : [
{
id: 1,
prod: "prod1",
price: "5"
},
{
id:2,
prod: "prod2",
price: "5"
}
]
}
export const searchProd = (state = initialState, action={}) =>{
console.log(action.payload);
console.log(action.type);
switch(action.type){
case CHANGE_SEARCH_FIELD:{
console.log(action.payload);
console.log(state.product);
return {...state, searchField: action.payload};}
default:
return state;
}
}
App.js
import React, { Component } from 'react';
import SignIn from './components/SignIn/SignIn';
import Register from './components/Register/Register';
import ListOfProd from './containers/ListOfProd';
import Search from './containers/Search';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Search></Search>
</div>
);
}
}
export default App;
Pleae let me know if you need to see my components.
In general, the best way to implement of filtration is on the key-down event on your text-box.
but before that you have to check your data source and think about your performance, you can set a key limitation or some other limitation.
for your second question, I should say that if your array is in your client use map to have the best performance but you have to get it from a server you can do many things

Categories

Resources