const [files, setFiles] = useState([]);
const onDrop = useCallback((acceptedFiles) => {
// Do something with the files
setFiles(
acceptedFiles.map((file: File) =>
Object.assign(file, {
preview: URL.createObjectURL(file),
})
)
);
}, []);
const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept: 'image/*',
multiple: false,
});
const thumbs = files.map((file: { [key: string]: string }) => (
<div className={classes.imagePreview} key={file.name}>
<img className={classes.image} src={file.preview} alt={file.name} />
</div>
));
useEffect(() => {
// Make sure to revoke the data uris to avoid memory leaks
files.forEach((file: { [key: string]: string }) =>
URL.revokeObjectURL(file.preview)
);
}, [files]);
My HTML
<div className={classes.imageContainer}>
{thumbs}
<div className={classes.borderBox} {...getRootProps()}>
<input {...getInputProps()} />
<div>
<AddIcon />
</div>
</div>
</div>
I am trying to upload via dropzone one at a time however my image gets replaced with the second one.
Fixed it with appending to the state
const onDrop = useCallback(
(acceptedFiles) => {
// Process files
const oneFile = get(acceptedFiles, '[0]', []);
Object.assign(oneFile, { preview: URL.createObjectURL(oneFile) });
setFiles([oneFile, ...files]);
},
[files]
);
Related
I'm making a todo app and using useState to pass value to the form then submit the todo but for some reasons my todo form is not render and i don't know what is missing in my codes, please help me to check! Thank you so much!
import React, { useState } from "react";
function Todo({ todo, index }) {
console.log("hiiii");
return (
<div>
<p>{todo.text}</p>
</div>
);
}
function todoForm(addTodo) {
const [value, setValue] = useState("");
handleSubmit = (e) => {
e.preventDefault();
if (!value) return;
addTodo(value);
setValue("");
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="add new todo"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
</form>
</div>
);
}
function App() {
const [todos, setTodos] = useState([
{
text: "eat lunch",
isCompleted: false
},
{
text: "do homework",
isCompleted: false
},
{
text: "go to school",
isCompleted: false
}
]);
addTodo = (text) => {
console.log("hey");
const newTodos = [...todos, { text }];
setTodos(newTodos);
};
return (
<div>
<div>
{todos.map((todo, index) => {
return <Todo key={index} index={index} todo={todo} />;
})}
</div>
<div>
<todoForm addTodo={addTodo} />
</div>
</div>
);
}
export default App;
Link sandbox: https://codesandbox.io/s/serverless-bash-ef4hk?file=/src/App.js
JSX tags must be uppercased in order to be properly parsed by the compiler as a React component.
Instead of todoForm, use TodoForm.
Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX expression, Foo must be in scope.
From: https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type
Also, you need to destructure props inside TodoForm in order to gain access to addTodo:
// Bad
function TodoForm(addTodo) {...}
// Good
function TodoForm({addTodo}) {...}
You should also assign you handlers to consts:
// Bad
addTodo = (text) => {...};
// Good
const addTodo = (text) => {...};
your problem is solved it
APP.JS
import React, { useState } from "react";
function Todo({ todo, index }) {
console.log("hiiii");
return (
<div>
<p>{todo.text}</p>
</div>
);
}
function todoForm(addTodo) {
const [value, setValue] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (!value) return;
addTodo(value);
setValue("");
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="add new todo"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
</form>
</div>
);
}
function App() {
const [todos, setTodos] = useState([
{
text: "eat lunch",
isCompleted: false
},
{
text: "do homework",
isCompleted: false
},
{
text: "go to school",
isCompleted: false
}
]);
const addTodo = (text) => {
console.log("hey");
const newTodos = [...todos, { text }];
setTodos(newTodos);
};
return (
<div>
<div>
{todos.map((todo, index) => {
return <Todo key={index} index={index} todo={todo} />;
})}
</div>
<div>
{todoForm(addTodo)}
</div>
</div>
);
}
export default App;
I Have external component managing my input Field and throws an error if no input is made.
On submit of form previously with class component along with reduxForm effect, this would throw an error of missing input, am wondering how to achieve this with hooks since submission passes whether i have input or Not.
import ConstructField from '../components.render';
const ActivitiesForm = () => {
const handleSubmit_ = () => {
console.log({ activityName });
};
const [activityName, setActivityName] = useState(null);
const handleInputName = (e) => setActivityName(e.target.value);
const { items } = useSelector((state) => ({
items: state.items,
}));
const { register, handleSubmit, errors, control } = useForm();
return (
<div>
<Form onSubmit={handleSubmit(handleSubmit_)} className='ui form'>
<Form.Group widths='equal'>
<Field
component={ConstructField('input')}
onChange={handleInputName}
label='Activity Name'
name='activityName'
placeholder='Activity Name'
validate={required}
/>
</Form.Group>
<br />
<Form.Group inline>
<Button.Group>
<Button primary>Save</Button>
<Button.Or />
<Button positive onClick={goBackButton}>
Go Back
</Button>
</Button.Group>
</Form.Group>
</Form>
</div>
);
};
const required = (value) => (value ? undefined : 'this field is required');
const activityform = reduxForm({
form: 'activityform',
enableReinitialize: true,
})(ActivitiesForm);
export default activityform;
I'm using React 16.13.0. I want to create a simple search component -- a single text box that as you type displays results. I have created the following component ...
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: "",
setSearchTerm: "",
searchResults: [],
setSearchResults: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const query = event.target.value;
if ( ! query ) {
this.setState({ searchTerm: query, searchResults: [] } );
} else {
this.setState({ searchTerm: query, loading: true }, () => {
this.doSearch(query);
});
}
}
doSearch = ( query ) => {
console.log("dosearch:" + query);
const searchUrl = '/coops/?contains=' + encodeURIComponent(query);
fetch(searchUrl,{
method: "GET"
}).then(response => response.json())
.then(data => {
console.log("query:" + query);
console.log(data);
this.setState({
searchResults: data,
loading: false,
});
});
};
renderSearchResults = () => {
const {searchResults} = this.state;
if (searchResults && searchResults.length) {
return (
<div className="results-container">
<div>Results</div>
<ul>
{searchResults.map(item => (
<li className="result-items" key={item.id} value={item.name}>{item.name}</li>
))}
</ul>
</div>
);
}
};
render() {
return (
<div className="searchForm">
<input
type="text"
placeholder="Search"
value={this.state.searchTerm}
onChange={this.handleChange}
/>
{ this.renderSearchResults() }
</div>
);
}
The issue is that if I type too fast, the fetch requests do not necessarily complete in the order they are sent out. For exmple, if my term is "south," the fetch corresponding to having typed "sou" may complete after I've fully typed "south," causing the results to be displayed incorrectly. How do I account for this and force my results to be displayed corresponding to the inputs typed?
You need to use onKeyUp={} this means that when user finished typing their search query only there you will start making the request.
<input
type="text"
placeholder="Search"
value={this.state.searchTerm}
onKeyUp={this.handleChange}
/>
Files don't get uploaded when I hit the upload method.
I believe this issue is due to the axios interceptors 'cause when I make a new axios instance and set the headers to
headers: {'Authorization': 'Bearer ' + this.user.api_token }
it works like a charm.
Is there any way to get this to work without creating a new axios instance? 'cause I don't have access to the user object in my ImageUploader component?
ImageUploader.vue
<template>
<div>
<label for="file">Select a file</label>
<input type="file" id="file" #change="onInputChange" multiple>
</div>
<div class="upload-control" v-show="images.length">
<label for="file">Select a file</label>
<button #click="upload">Upload</button>
</div>
<template/>
<script>
export default {
data: () => ({
files: [],
images: []
}),
methods: {
onInputChange(e) {
const files = e.target.files;
Array.from(files).forEach(file => this.addImage(file));
},
addImage(file) {
if (!file.type.match('image.*')) {
this.$toastr.e(`${file.name} is not an image`);
return;
}
this.files.push(file);
const img = new Image(),
reader = new FileReader();
reader.onload = (e) => this.images.push(e.target.result);
reader.readAsDataURL(file);
},
upload() {
const formData = new FormData();
this.files.forEach(file => {
formData.append('images[]', file, file.name);
});
axios.post('/api/products', formData)
.then(response => {
this.images = [];
this.files = [];
})
},
},
}
App.vue
<script>
import SearchBar from "./SearchBar";
export default {
name: "App",
props: [
'user'
],
components: {
SearchBar
},
created() {
this.title = this.$route.meta.title;
window.axios.interceptors.request.use(config => {
if (config.method === "get") {
config.url = config.url + "?api_token=" + this.user.api_token;
} else {
config.data = {
...config.data,
api_token: this.user.api_token
};
}
return config;
});
},
}
</script>
I have 2 of the same components in my laravel blade view, but they are conflicting.
What i'm trying to accomplish:
I've made a vue component that uploads a file to firebase and stores it in my database. In my blade view i have 2 places where i want to use this component. I configure the component with props so the component knows where to store the file.
What going wrong:
Every time i try to upload a file with the second component, i fire the function in the first component. How do i fix that the components can't conflict?
My laravel balde view:
component 1
<uploadfile
:key="comp100"
:user_data="{{ Auth::user()->toJson() }}"
store_path="/users/{{ Auth::user()->username }}/settings/email_backgrounds"
:store_route="'settings.project_email'"
:size="1000"
fillmode="cover"
></uploadfile>
component 2
<uploadfile
:key="comp200"
:user_data="{{ Auth::user()->toJson() }}"
store_path="/users/{{ Auth::user()->username }}/settings/email_backgrounds"
:store_route="'settings.project_email'"
:size="1000"
fillmode="cover"
></uploadfile>
The Vue component:
<template>
<div class="vue-wrapper">
<FlashMessage position="right top"></FlashMessage>
<div v-if="loading" class="lds-dual-ring"></div>
<div class="field">
<div class="control">
<label class="button main-button action-button m-t-20" for="uploadFiles"><span style="background-image: url('/images/icons/upload.svg')"></span>Kies bestand</label>
<input type="file" name="uploadFiles" id="uploadFiles" class="dropinput" #change="selectFile">
</div>
</div>
</div>
</template>
<script>
import { fb } from '../../firebase.js';
export default {
data() {
return {
fileObject: {
filePath: null,
url: null,
file: null,
resizedPath: null
},
loading: false
};
},
mounted() {
console.log(this.size)
console.log(this.fillmode)
},
props: [
'user_data',
'store_path',
'store_route',
'size',
'fillmode'
],
methods: {
selectFile(event)
{
var file = event.target.files[0];
this.fileObject.file = file
this.fileObject.filePath = this.store_path + '/' + file.name
this.fileObject.resizedPath = this.store_path + '/resized-' + file.name
if(file.type == 'image/png' || file.type == 'image/jpeg')
{
this.uploadFile(this.fileObject)
} else {
this.flashMessage.success({
title: 'Oeps!',
message: 'De afbeelding moet een png of een jpeg zijn!',
blockClass: 'success-message'
});
}
},
uploadFile(fileObject)
{
var vm = this
console.log(fileObject)
var storageRef = fb.storage().ref(fileObject.filePath)
var uploadTask = storageRef.put(fileObject.file)
this.loading = true
uploadTask.on('state_changed', function(snapshot){
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},function(error) {
}, function() {
var resizeImage = fb.functions().httpsCallable('resizeImage')
resizeImage({filePath: fileObject.filePath, contentType: fileObject.file.type, watermark: false, size: vm.size, fit: vm.fillmode}).then(function(result){
var downloadRef = fb.storage().ref(fileObject.resizedPath);
downloadRef.getDownloadURL().then(function(url){
fileObject.url = url
vm.loading = false
vm.storeImage(fileObject)
}).catch(function(error){
console.log(error)
})
}).catch(function(error){
});
});
},
storeImage(file)
{
axios.post('/api/app/store_file', {
api_token: this.user_data.api_token,
user: this.user_data,
file: file,
storeRoute: this.store_route
}).then((res) => {
location.reload()
}).catch((e) => {
});
}
}
}
</script>
Does someone know how to fix this?