Skip to content

Commit

Permalink
CRUD in frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
aatmanvaidya committed Sep 14, 2023
1 parent 5170b76 commit d867dbe
Show file tree
Hide file tree
Showing 10 changed files with 337 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,12 @@ module.exports = {
},
label: {
type: Sequelize.STRING,
allowNull: false,
},
labelMeaning: {
type: Sequelize.TEXT,
allowNull: false,
},
appropriated: {
type: Sequelize.BOOLEAN,
allowNull: false,
},
appropriationContext: {
type: Sequelize.STRING,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ module.exports = {
},
category: {
type: Sequelize.ENUM(['gender', 'religion', 'caste']),
allowNull: false,
},
createdAt: {
allowNull: false,
Expand Down
1 change: 0 additions & 1 deletion browser-extension/api-server/db/models/category.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ module.exports = (sequelize, DataTypes) => {
},
category : {
type: DataTypes.ENUM(['gender', 'religion', 'caste']),
allowNull: false,
},
},
{
Expand Down
3 changes: 0 additions & 3 deletions browser-extension/api-server/db/models/slur.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,12 @@ module.exports = (sequelize, DataTypes) => {
},
label: {
type: DataTypes.STRING,
allowNull: false,
},
labelMeaning: {
type: DataTypes.TEXT,
allowNull: false,
},
appropriated: {
type: DataTypes.BOOLEAN,
allowNull: false,
},
appropriationContext: {
type: DataTypes.STRING,
Expand Down
13 changes: 6 additions & 7 deletions browser-extension/api-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ app.get("/auth/register", async (req, res) => {
const newUser = await registerAnonymousUser();
res.send({ user: newUser });
} catch (err) {
console.log(err)
res.status(501).send();
}
});
Expand Down Expand Up @@ -214,12 +215,7 @@ app.get("/slur", async (req, res) => {
},
],
});

if (results) {
res.status(500).send({ error: "error finding slurs" });
} else {
res.json(results);
}
res.json(results);
} catch (error) {
console.error(error);
res.status(500).send({ error: "server error" });
Expand All @@ -228,7 +224,10 @@ app.get("/slur", async (req, res) => {

// POST request for slur and category
app.post("/slur/create", async (req, res) => {
const { userId, label, labelMeaning, appropriated, appropriationContext, categories } = req.body;
const { user } = req
const userId = user.id
const { label, labelMeaning, appropriated, appropriationContext, categories } = req.body;
console.log(userId, label, labelMeaning, appropriated, appropriationContext, categories)
// const t = await Op.transaction();
const t = await sequelize.transaction()

Expand Down
7 changes: 2 additions & 5 deletions browser-extension/plugin/src/ui-components/pages/Api.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,14 @@ async function getSlurAndCategory(accessToken) {
Authorization: `token ${accessToken}`
}
});
console.log('GET slur and category data', result.data);
return result.data;
}

// POST request for slur and category
async function createSlurAndCategory(accessToken, slurData) {
return axios.post(`${API_URL}/slur/create`, slurData, {
headers: {
Authorization: `token ${accessToken}`,
'Content-Type': 'multipart/form-data'
Authorization: `token ${accessToken}`
}
});
}
Expand All @@ -124,8 +122,7 @@ async function createSlurAndCategory(accessToken, slurData) {
async function updateSlurAndCategory(accessToken, slurId, updatedData) {
return axios.put(`${API_URL}/slur/${slurId}`, updatedData, {
headers: {
Authorization: `token ${accessToken}`,
'Content-Type': 'multipart/form-data'
Authorization: `token ${accessToken}`
}
});
}
Expand Down
5 changes: 5 additions & 0 deletions browser-extension/plugin/src/ui-components/pages/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { ToggleSwitchCustom } from '../atoms/ToggleSwitchCustom';
import { Off } from './Off';
import { Slur } from './Slur';
import SlurCreate from './SlurCreate';
import SlurEdit from './SlurEdit';

export function App() {
const [user, setUser] = useState(undefined);
Expand Down Expand Up @@ -252,6 +253,10 @@ export function App() {
path="slur/create"
element={<SlurCreate />}
/>
<Route
path="slur/:id"
element={<SlurEdit />}
/>
</Routes>
</div>
) : (
Expand Down
61 changes: 59 additions & 2 deletions browser-extension/plugin/src/ui-components/pages/Slur.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import { useNavigate } from 'react-router-dom';
import Api from './Api';
import { UserContext } from '../atoms/AppContext';

const { getSlurAndCategory } = Api;
const { getSlurAndCategory, deleteSlurAndCategory } = Api;

export function Slur() {
let navigate = useNavigate();
const [, setGetSlurs] = useState([]);
const [getSlurs, setGetSlurs] = useState([]);
const { user } = useContext(UserContext);
// const { notification, showNotification } = useContext(NotificationContext);

Expand All @@ -25,6 +25,14 @@ export function Slur() {
console.error('error fetching slurs', error);
}
}
async function handleDeleteSlur(slurId) {
try {
await deleteSlurAndCategory(user.accessToken, slurId);
fetchSlurs();
} catch (err) {
console.error('could not delete slur', err);
}
}

useEffect(() => {
fetchSlurs();
Expand All @@ -43,6 +51,55 @@ export function Slur() {
<Box alignContent="center">
<Text textAlign="center">Your Crowdsourced Slur List</Text>
</Box>
<Box gap="medium" alignContent="center" wrap>
{getSlurs.map((slur, index) => (
<Box
key={index}
background="light-2"
pad="medium"
round="small"
width="medium"
elevation="small"
>
<Box direction="row" justify="end">
<Button
label="Edit"
onClick={() => navigate(`/slur/${slur.id}`)}
/>
<Button
label="Delete"
onClick={() => handleDeleteSlur(slur.id)}
/>
</Box>
<Text>
<strong>Label:</strong> {slur.label}
</Text>
<Text>
<strong>Label Meaning:</strong> {slur.labelMeaning}
</Text>
<Text>
<strong>Appropriated:</strong>{' '}
{slur.appropriated ? 'Yes' : 'No'}
</Text>
<Text>
<strong>Appropriation Context:</strong>{' '}
{slur.appropriationContext}
</Text>
<Text>
<strong>Categories:</strong>
<ul>
{slur.categories.map(
(category, categoryIndex) => (
<li key={categoryIndex}>
{category.category}
</li>
)
)}
</ul>
</Text>
</Box>
))}
</Box>
</Box>
);
}
101 changes: 87 additions & 14 deletions browser-extension/plugin/src/ui-components/pages/SlurCreate.jsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,78 @@
import { useState } from 'react';
import { useState, useContext } from 'react';
import {
Box,
Button,
Form,
FormField,
Heading,
RadioButtonGroup,
Select,
CheckBox,
TextArea,
TextInput,
Anchor
} from 'grommet';
import { useNavigate } from 'react-router-dom';
import Api from './Api';
import { UserContext } from '../atoms/AppContext';

const category = ['gender', 'religion', 'caste'];
const { createSlurAndCategory } = Api;

const categoryOptions = ['gender', 'religion', 'caste'];
const appropriatedOptions = [true, false];

export function SlurCreate() {
const { user } = useContext(UserContext);
console.log('user id', user.id);
// console.log("user token", user.accessToken)
// const { notification, showNotification } = useContext(NotificationContext);
const initialFormData = {
label: '',
labelMeaning: '',
category: '',
categories: [],
appropriated: false,
appropriationContext: ''
};
const [formData, setFormData] = useState(initialFormData);

const navigate = useNavigate();
const handleGoBack = () => {
navigate('/slur');
};

const handleSubmit = (value) => {
console.log(value);
console.log(formData);
const handleSubmit = async () => {
try {
const categories = formData.categories.map((category) => ({
category
}));
const requestData = {
...formData,
categories
};
console.log(requestData);
const response = await createSlurAndCategory(
user.accessToken,
requestData
);
await setFormData({
...response.data
});
navigate('/slur');
} catch (error) {
console.error('Error creating slur:', error);
}
};
const handleReset = () => {
setFormData(initialFormData);
};
const handleCategoryChange = (category) => {
const updatedCategories = formData.categories.includes(category)
? formData.categories.filter((c) => c !== category)
: [...formData.categories, category];
setFormData({
...formData,
categories: updatedCategories
});
};

return (
<Box>
Expand All @@ -47,25 +83,53 @@ export function SlurCreate() {
<Form
value={formData}
onChange={(nextValue) => setFormData(nextValue)}
onSubmit={handleSubmit}
onSubmit={({ value }) => {
handleSubmit(value);
}}
>
<FormField name="label" label="Label" required>
<TextInput name="label" />
<TextInput
name="label"
value={formData.label}
onChange={(e) =>
setFormData({ ...formData, label: e.target.value })
}
/>
</FormField>

<FormField name="labelMeaning" label="Label Meaning" required>
<TextArea name="labelMeaning" />
<TextArea
name="labelMeaning"
value={formData.labelMeaning}
onChange={(e) =>
setFormData({
...formData,
labelMeaning: e.target.value
})
}
/>
</FormField>

<FormField name="category" label="Category" required>
<Select name="category" options={category} />
<FormField name="categories" label="Categories" required>
<Box direction="row" margin="small">
{categoryOptions.map((category) => (
<CheckBox
key={category}
label={category}
name="categories"
checked={formData.categories.includes(category)}
onChange={() => handleCategoryChange(category)}
/>
))}
</Box>
</FormField>

<FormField name="appropriated" label="Appropriated" required>
<RadioButtonGroup
name="appropriated"
options={appropriatedOptions}
defaultValue={false}
direction="row"
value={formData.appropriated}
/>
</FormField>

Expand All @@ -74,7 +138,16 @@ export function SlurCreate() {
label="Appropriation Context"
required
>
<TextInput name="appropriationContext" />
<TextInput
name="appropriationContext"
value={formData.appropriationContext}
onChange={(e) =>
setFormData({
...formData,
appropriationContext: e.target.value
})
}
/>
</FormField>

<Box direction="row" gap="medium">
Expand Down
Loading

0 comments on commit d867dbe

Please sign in to comment.